https://kotlinlang.org logo
#coroutines
Title
# coroutines
l

Lukas Lechner

10/03/2022, 8:52 AM
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

simon.vergauwen

10/03/2022, 8:56 AM
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

Lukas Lechner

10/03/2022, 9:03 AM
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

Robert Williams

10/03/2022, 9:10 AM
runBlocking needs to throw because it can return a result which won't be available if the coroutine is cancelled
j

Jhonatan Sabadi

10/04/2022, 11:17 AM
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

simon.vergauwen

10/04/2022, 11:19 AM
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
32 Views