ChannelIterator

interface ChannelIterator<out E>(source)

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
}

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")
}
}

Possible output:

Consumer A got 1
Consumer A got 2
Consumer B got 3

Functions

Link copied to clipboard
abstract suspend operator fun hasNext(): Boolean

Prepare an element for retrieval by the invocation of next.

Link copied to clipboard
abstract operator fun next(): E

Retrieves the element removed from the channel by the preceding call to hasNext, or throws an IllegalStateException if hasNext was not invoked.