Taking more elements than those available

With iterators and sequences, trying to retrieve more elements than those possible to yield would result in an exception of the type NoSuchElementException.

With producers, on the other hand, it depends on how you are trying to obtain that element. For example, given a channel that can emit up to 10 elements, the following code would not fail:

producer.take(12).consumeEach {
println(it)
}

This is because consumeEach will stop once there are no more elements, regardless of how many we intended to take. If we modify the code to add another receive() for another element, the application will crash:

producer.take(12).consumeEach {
println(it)
}

val element = producer.receive()

It will crash because once the producer has completed its execution, the channel is closed. So, the exception being thrown is ClosedReceiveChannelException:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.223.210.71