toList
Returns a List containing all the elements sent to this channel, preserving their order.
This function will attempt to receive elements and put them into the list until the channel is closed. Calling toList on channels that are not eventually closed is always incorrect:
It will suspend indefinitely if the channel is not closed, but no new elements arrive.
If new elements do arrive and the channel is not eventually closed, toList will use more and more memory until exhausting it.
If the channel is closed with a cause, toList will rethrow that cause.
The operation is terminal. This function consumes all elements of the original ReceiveChannel.
Example:
val values = listOf(1, 5, 2, 9, 3, 3, 1)
// start a new coroutine that creates a channel,
// sends elements to it, and closes it
// once the coroutine's body finishes
val channel = produce {
values.forEach { send(it) }
}
check(channel.toList() == values)
Content copied to clipboard