ArrayChannel

This type of channel has a buffer size bigger than zero and up to Int.MAX_VALUE - 1, and will suspend the senders when the amount of elements it contains reaches the size of the buffer. It can be created by sending any positive value lower than Int.MAX_VALUE to Channel():

val channel = Channel<Int>(50)

It can also be created by calling its constructor directly:

val arrayChannel = ArrayChannel<Int>(50)

This type of channel will suspend the sender when the buffer is full, and resume it when one or more of the items is retrieved, as the following for example:

fun main(args: Array<String>) = runBlocking {
val time = measureTimeMillis {
val channel = Channel<Int>(4)
val sender = launch {
repeat(10) {
channel.send(it)
println("Sent $it")
}
}

delay(500)
println("Taking two")
channel.take(2).receive()
delay(500)
}

println("Took ${time}ms")
}

In this example, sender is able to emit up to 10 elements, but because the capacity of the channel is four, it will be suspended before sending the fifth element. Once two elements are received, sender is resumed until the buffer is full again:

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

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