I notice a strange behavior when trying to prematurely cancel from a Flow. Take a look at the following example.
This is a simple flow that emits integer values
I came across a workaround in this related issue
I have replaced every single collect
with a safeCollect
function in my project:
/**
* Only proceed with the given action if the coroutine has not been cancelled.
* Necessary because Flow.collect receives items even after coroutine was cancelled
* https://github.com/Kotlin/kotlinx.coroutines/issues/1265
*/
suspend inline fun Flow.safeCollect(crossinline action: suspend (T) -> Unit) {
collect {
coroutineContext.ensureActive()
action(it)
}
}