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

Jacques Smuts

08/15/2019, 6:52 PM
I actually have a question related to the awaitClose block. I’m playing around with the above code and I noticed that if the CoroutineContext that is suspended on
.collect
gets cancelled, then the
awaitClose
block gets called. However if a CoroutineContext is suspended on a Channel’s
.receive()
and gets cancelled, then the
invokeOnClose
on that Channel does not get called. You have to manually close the channel. Is that expected behaviour? There’s no automatic propagation of Coroutine cancellation into Channels?
l

louiscad

08/15/2019, 6:55 PM
It is normal behavior. If you want to close the channel on cancellation or completion, you need to use
consume { … }
and call
receive()
inside its lambda, or use
consumeEach
straightaway.
j

Jacques Smuts

08/15/2019, 7:01 PM
And it works
thank you
I find that a little dangerous though. It isn’t obvious that cancellation on
consume
propagates, but
receive
doesn’t 🤔
l

louiscad

08/15/2019, 7:24 PM
A Channel is only closed explicitly, using
close
,
cancel
,
consume
or
consumeEach
. You might have multiple coroutines calling
receive
. Cancelling one shouldn't close the channel for the remaining.
j

Jacques Smuts

08/15/2019, 7:34 PM
I see that
consume
lists that in the documentation. This all makes sense, there’s just a lot of discovery and reading left for me. Thanks for educating 🙂
7 Views