RendezvousChannel

Currently the only implementation of unbuffered channels is RendezvousChannel. This implementation of a channel has no buffer at all, so calling send() on it will suspend it until a receiver calls receive() on the channel. You can instantiate this type of channel in a few different ways. You can do it by calling its constructor:

val channel = RendezvousChannel<Int>()

You can also use the Channel() function. This function has two implementations, one that takes the buffer capacity as parameter, and another that doesn't take any parameters. To get a RendezvousChannel you can call the function without a parameter:

val rendezvousChannel = Channel<Int>()

You will have the same result if you send a capacity of zero:

val rendezvousChannel = Channel<Int>(0)

As mentioned, this channel will suspend the sender's execution until the element on it is retrieved, as the following for example:

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

channel.receive()
channel.receive
()
}

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

In this example, the sender coroutine can send up to 10 numbers through the channel. But because only two of the elements are received from the channel before the execution ends, only two elements are sent.

The output of this coroutine looks like the following:

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

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