https://kotlinlang.org logo
#coroutines
Title
# coroutines
a

ahmad

07/24/2020, 7:34 PM
Hello I have a simple question
Copy code
fun main() {
    val observable = Observable.create<Int> { emitter ->
        for (i in 1..5) {
            emitter.onNext(i)
        }
        emitter.onComplete()
    }
    observable.asFlow().onEach {
        println("Flow: $it")
    }
}
Why this code doesn’t print anything?
o

octylFractal

07/24/2020, 7:35 PM
onEach
is not a terminal operator, you probably want
collect
(extension function variant, not the internal coroutines API)
note that
collect
requires a
suspend
context, so you will probably also need
suspend fun main
a

ahmad

07/24/2020, 7:36 PM
I tried that
Copy code
fun main() {
    val observable = Observable.create<Int> { emitter ->
        for (i in 1..5) {
            emitter.onNext(i)
        }
        emitter.onComplete()
    }

    GlobalScope.launch {
        observable.asFlow().collect {
            println("Flow: $it")
        }
    }
}
It didn’t print anything
o

octylFractal

07/24/2020, 7:37 PM
yes, because
launch
is async --
main
is exiting before
launch
gets to start
a

ahmad

07/24/2020, 7:38 PM
Aha okay .. thank you 🙏
m

Marcelo Hernandez

07/24/2020, 8:24 PM
Have you tried using
runBlocking
?
o

octylFractal

07/24/2020, 8:27 PM
runBlocking
is another solution, it's similar to
suspend fun main
a

ahmad

07/24/2020, 8:36 PM
yes got it .. thanks guys
2 Views