How can I cancel flow collection from within the `...
# coroutines
l
How can I cancel flow collection from within the
collect{}
operator? The docs say that it should be possible to call
cancel()
, but that doesn’t seem to work….
s
Where is the
cancel()
coming from in that case? 🤔
throw CancellationException
is the first thing that comes to mind, which then probably ends up in a
launch
or
launchIn
and then the behavior depend on the surrounding
CoroutineScope
impl. What is your use-case for this?
l
Ahh, okay, the docs use
runBlocking{}
, and there we have
coroutineScope
as receiver, on which cancel can be called.
However I wonder why there is a crash in this case when a
CancellationException
is thrown 🤔 Aren’t
CancellationExceptions
special kind of exceptions that don’t lead to crashes?
r
runBlocking needs to throw because it can return a result which won't be available if the coroutine is cancelled
j
It's important to cancel and use "ensureactive" on the emitter, if you don't do that, you can cancel and flow still send
s
You can also compose this after the fact by calling
cancellable
it will inject
ensureActive()
in between calls to
emit
. https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/cancellable.html