Shmuel Rosansky [G]
01/17/2021, 5:42 PMfun main() {
println("Outer")
CoroutineScope(Dispatchers.Default).launch {
getFlow()
.onEach { println("Value: $it") }
.collect()
}
}
fun getFlow() = callbackFlow<Int> {
println("Inner")
delay(1)
sendBlocking(0)
}
Shouldn't Outer
get printed first?Marc Knaup
01/17/2021, 5:55 PMOuter
and exits. That’s correct.
If I make main
wait a little after launching the coroutine the program terminates with an error:
Outer
Inner
Value: 0
Exception in thread "DefaultDispatcher-worker-1" java.lang.IllegalStateException: 'awaitClose { yourCallbackOrListener.cancel() }' should be used in the end of callbackFlow block.
Otherwise, a callback/listener may leak in case of external cancellation.
See callbackFlow API documentation for the details.
Shmuel Rosansky [G]
01/17/2021, 5:57 PMMarc Knaup
01/17/2021, 5:58 PMInner Outer
without anything else. Also correct.
You run both in parallel so there’s no guarantee which one will happen first. Printing output isn’t always synchronous.Shmuel Rosansky [G]
01/17/2021, 5:59 PMprintln
?Marc Knaup
01/17/2021, 6:00 PMShmuel Rosansky [G]
01/17/2021, 6:00 PM