'Emit after cancellation in Kotlin flow
I have a more complex version of the following code:
val testFlow = flow {
try {
// Continually emit some values
} catch (e: CancellationException) {
// Wrap up and emit finished state value
}
}
When I collect this testFlow, I never receive the finished state value. It is documented that the flow builder performs ensureActive checks before emitting values. In this link is also an example using IntRange.asFlow that does not check for cancellation before emitting values and showing that those values are continued to be collected.
Is there a way to make a custom kotlin flow emit a last value to be collected after the cancellation of the coroutine?
Here's a Kotlin Playground example (thanks @Tenfour04) showing differing behaviour of emit after cancel depending on how the flow is constructed. I just don't know how to get a flow that's able to emit after cancel that is not constructed by IntRange.asFlow.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
