ahmad
07/24/2020, 7:34 PMfun 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?octylFractal
07/24/2020, 7:35 PMonEach
is not a terminal operator, you probably want collect
(extension function variant, not the internal coroutines API)octylFractal
07/24/2020, 7:35 PMcollect
requires a suspend
context, so you will probably also need suspend fun main
ahmad
07/24/2020, 7:36 PMfun 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 anythingoctylFractal
07/24/2020, 7:37 PMlaunch
is async -- main
is exiting before launch
gets to startahmad
07/24/2020, 7:38 PMMarcelo Hernandez
07/24/2020, 8:24 PMrunBlocking
?octylFractal
07/24/2020, 8:27 PMrunBlocking
is another solution, it's similar to suspend fun main
ahmad
07/24/2020, 8:36 PM