Slava
Slava

Reputation: 717

How can I call flow method from Java code

How can I call flow method from Java code.

fun getAllUsers(): Flow<List<User>> =
        userRepositoryImpl.getAllUsers()

from Java

private Observable<List<User>> getUsers() {
  subscriber.onNext(userViewModel.getAllUsers()); //example
}

Upvotes: 0

Views: 497

Answers (1)

ObscureCookie
ObscureCookie

Reputation: 1128

If what you want to do is collecting a flow, you can do like this.

Define coroutine helper functions in a Kotlin file.

object JavaFlow {
    @JvmStatic
    fun <T> collectInJava(
        scope: CoroutineScope,
        flow: Flow<T>,
        action: (T) -> Unit
    ): Job {
        return scope.launch {
            flow.collect {
                action(it)
            }
        }
    }

    // this function is just for testing
    @JvmStatic
    fun getFlow(from: Int, to: Int): Flow<Int> = flow {
        val range = from until to

        range.forEach {
            delay(50)
            emit(it)
        }
    }
}

then In Java, you can call collectInJava to collect a flow.

public class JavaMain {
    public static void main(String[] args) {
        Flow<Integer> flow = JavaFlow.getFlow(0, 5);
        CoroutineScope scope = () -> EmptyCoroutineContext.INSTANCE; // create a new scope

        JavaFlow.collectInJava(
                scope,
                flow,
                (i) -> {
                    System.out.println(i);
                    return Unit.INSTANCE;
                }
        );

        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}

Upvotes: 1

Related Questions