Channels

Up until now, we learned how to spawn coroutines and control them. But what if two coroutines need to communicate with each other?

In Java, threads communicate either by using the wait()/notify()/notifyAll() pattern or by using one of the rich set of classes from the java.util.concurrent package. For example: BlockingQueue or Exchanger.

In Kotlin, as you may have noticed, there are no wait()/notify() methods. But there are channels, which are very similar to BlockingQueue. But instead of blocking a thread, channels suspend a coroutine, which is a lot cheaper.

To understand channels better, let's create a simple game of two players that will throw random numbers at each other. If your number is greater, you win. Otherwise, you lose the round:

fun player(name: String,
input: Channel<Int>,
output: Channel<Int>) = launch {
for (m in input) {
val d = Random().nextInt(100)
println("$name got $m, ${if (d > m) "won" else "lost" }")

delay(d)
output.send(d)
}
}

Each player has two channels. One is used to receive data, the other to send it. 

We can iterate over a channel with a regular for-loop, which will suspend until the next value is received.

When we want to send our results to the other player, we simply use the send() method.

Now let's play this game for one second:

fun main(vararg args: String) {
val p1p2 = Channel<Int>()
val p2p1 = Channel<Int>()

val player1 = player("Player 1", p2p1, p1p2)
val player2 = player("Player 2", p1p2, p2p1)

runBlocking {
p2p1.send(0)
delay(1000)
}
}

Our output may look something like this:

...
Player 1 got 62, won
Player 2 got 65, lost
Player 1 got 29, lost
Player 2 got 9, won
Player 1 got 46, won
Player 2 got 82, lost
Player 1 got 81, lost
...

As you can see, channels are a convenient and type-safe way to communicate between different coroutines. But we had to define the channels manually, and pass them in the correct order. In the next two sections, we'll see how this can be further simplified.

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

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