What is the difference between channel.fori and ch...
# coroutines
m
What is the difference between channel.fori and channel.consumeEach ?
s
consumeEach
will call
cancel()
on the channel after you're done iterating. The main situation where that differs from a regular
for
loop is if the iteration ends early, for example due to an exception or control flow statement in the loop body. A
for
loop can stop iterating while leaving the channel open for future items, but
consumeEach
will always leave the channel in a closed state.
If the iteration just runs without interruption until the channel is closed, there's no real difference between the two approaches.
m
what does it mean: ‘consumeEach’ will cancel? consumeEach won’t return until the sender closes the channel
what is the meaning of a consumer closing the channel. this part i dont get
s
A channel can be closed either by the sender calling
close()
or by the consumer calling
cancel()
. You're right that
consumeEach
won't normally return until the sender closes the channel, but there are cases where that's not true. For example:
Copy code
channel.consumeEach {
    throw Exception("There was an error")
}
If an exception is thrown from
consumeEach
, the iteration stops and won't process any more items. In that case, the
consumeEach
function will automatically call
cancel()
to close the channel before letting the error propagate.
m
oh ok. now i get it. Thanks! the docs don’t state that
👆 1