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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access