I actually have a question related to the awaitClo...
# coroutines
j
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
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
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
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
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 🙂