How to collect a coroutine flow in java?
Asked Answered
E

3

7

I'm developing an Android library,

When the user receives a push notification it may contain deep links, that I need to return to the app.

I did in kotlin with no problem.

This is the function that is called when it needs to send the deep links

fun getDeepLinkFlow(): Flow<HashMap<String, String>?> = flow {
    emit(deepLinks)
}

And in my kotlin test app I managed to use with no problems as well, using like this.

GlobalScope.launch(coroutineContext) {
    SDK.getDeepLinkFlow().collect { deepLinks ->
        println(deepLinks)
    }
}

But now, there's a RN project that whant to use the lib, in order to do that we are doing a RN module that joins the iOS code and the Android code. But it uses java.

So, how can I use the collect from Coroutines on a Java code? or what could I do differently?

Esra answered 27/5, 2020 at 18:20 Comment(0)
S
1

Coroutines/Flow is inherently awkward to use from Java since it relies on transformed suspend code to work.

One possible solution is to expose an alternative way of consuming the Flow to your java code. Using the RxJava integration library you can expose a compatible Flowable that the java side can consume.

Syncopated answered 27/5, 2020 at 18:39 Comment(0)
E
1

I've decided to change the way deep links were used and start using the ViewModel with a liveData instead.

Esra answered 29/5, 2020 at 12:31 Comment(0)
L
0

As an alternative, if you're handling it on an activity or fragment a way to do this is using an extension function with a callback. Here's an example:

Kotlin extension:

fun MyActivity.observeScreenState(callbackToJava: (ScreenState) -> Unit) {
    lifecycleScope.launch {
        viewModel.screenState.collect {
            callbackToJava(it)
        }
    }
}

Java code:

observeScreenState(
    this,
    (ScreenState state) -> {
        doWhatever(state);
        return null;
    }
);
Lightfingered answered 9/3 at 18:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.