Channels
Learn how channels are needed to communicate between coroutines in Kotlin and what are producers and actors used for.
We'll cover the following...
Channels
We now know 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()
or notify()
or notifyAll()
pattern or by using one of the rich set of classes from the java.util.concurrent
package—for example, BlockingQueue
.
In Kotlin, as you may have noticed, there are no wait()
or notify()
methods. Instead, to communicate between coroutines, Kotlin uses channels. Channels are very similar to BlockingQueue
, but instead of blocking a thread, channels suspend a coroutine, which is a lot cheaper. We’ll use the following steps to create a channel and a coroutine.
-
First, let’s create a channel:
Channels are typed. This channel can only ...