Can some1 help me understand when the awaitClose g...
# coroutines
m
Can some1 help me understand when the awaitClose gets called:
Copy code
@Test
fun `test flow` (): Unit = runBlocking{
    val flow = callbackFlow {
        trySend(Unit)
        delay(5000)
        close()

        awaitClose {
            println("Closed")
        }
    }

    val job = launch {
        flow.collect {  }
    }
    job.cancel()
}
The doc says on close and cancellation. But in this case, it is not called. Why ? When it is cancelled, awaitClose not called.
j
My guess is that the collector is cancelled when the flow is still in the
delay()
so the flow's body doesn't even have the time to register the
awaitClose
callback, nor to close the underlying channel of the
callbackFlow
. To be fair that's not really how
callbackFlow
is designed to be used (it's rather meant to wrap listener based APIs)
m
oh ya, you are right! Yes, i know đŸ˜› I just used the delay to try check if the awaitClose really get’s called on cancellation
thanks!
j
If you want to test that I suggest you remove the delay and the
close()
call.
awaitClose()
will actually wait for cancellation