Is it just me, or is this a really poorly worked K...
# coroutines
w
Is it just me, or is this a really poorly worked KDoc:
Copy code
/**
 * Performs the given [action] for each received element and [cancels][ReceiveChannel.cancel]
 * the channel after the execution of the block.
 * If you need to iterate over the channel without consuming it, a regular `for` loop should be used instead.
 *
 * The operation is _terminal_.
 * This function [consumes][ReceiveChannel.consume] all elements of the original [ReceiveChannel].
 */
public suspend inline fun <E> ReceiveChannel<E>.consumeEach(action: (E) -> Unit): Unit =
    consume {
        for (e in this) action(e)
    }
... and cancels the channel after execution of the block.
The given block will typically be executed many times before the channel is cancelled, right?
👍 1
s
I can see why the wording would be confusing. Yes, the
action
runs once for each item in the queue. Maybe it'd be better if it said that it cancels the channel if the
action
throws an exception, since in practice that's the only time it could exit without the channel being already closed.
l
That's not the only way. The other way is the function calling consumeEach gets cancelled, and the code behind the suspend iterator for loop throws a CancellationException.
s
👍 true, thanks, I missed that
a
I'm helping with the documentation overhaul. Here's my attempt to explain the actual behavior: https://github.com/Kotlin/kotlinx.coroutines/pull/4148/files#diff-6979732c80522244d3bb2e0df43b3037c9836dfef082d6bada22f54830f7494cR107
it cancels the channel if the
action
throws an exception, since in practice that's the only time it could exit without the channel being already closed.
Actually, there is one more way: https://github.com/Kotlin/kotlinx.coroutines/blob/1bffe67a32d9d0285320f5b23fa94bc2[…]92e/kotlinx-coroutines-core/common/test/channels/ConsumeTest.kt
l
True, non local return is also a way.