ChannelIterator
Iterator for a ReceiveChannel. An instance of this interface is not thread-safe. Multiple coroutines are allowed to create and use their own instances of this interface for the same channel.
Typically, an iterator is used indirectly in the for loop and is not instantiated explicitly.
for (element in channel) {
// process the element
}Content copied to clipboard
If your use-case requires handling the iterator directly, you must call hasNext before each next. Refer to hasNext and next for more details.
An example usage:
val channel = Channel<Int>()
launch {
channel.send(1)
channel.send(2)
channel.send(3)
channel.close() // NB: must close for iterators to finish
}
launch {
for (element in channel) {
println("Consumer A got $element")
}
}
launch {
for (element in channel) {
println("Consumer B got $element")
}
}Content copied to clipboard
Possible output:
Consumer A got 1
Consumer A got 2
Consumer B got 3Content copied to clipboard