Wesley Hartford
06/04/2024, 12:36 AM/**
* 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?
Sam
06/04/2024, 8:20 AMaction
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.louiscad
06/04/2024, 8:22 AMSam
06/04/2024, 8:24 AMAwkin
06/04/2024, 2:20 PMit cancels the channel if theActually, there is one more way: https://github.com/Kotlin/kotlinx.coroutines/blob/1bffe67a32d9d0285320f5b23fa94bc2[…]92e/kotlinx-coroutines-core/common/test/channels/ConsumeTest.ktthrows an exception, since in practice that's the only time it could exit without the channel being already closed.action
louiscad
06/04/2024, 2:44 PM