Channels
In the last chapter, we explored how to create and manage coroutines. Now, what if you need these coroutines to talk to each other?
Java threads typically communicate using the wait()
/notify()
/notifyAll()
pattern or through specialized classes like BlockingQueue
from the java.util.concurrent
package. Kotlin takes a different approach: it doesn’t have wait()
or notify()
methods at all. Instead, it uses a feature called channels for communication between coroutines.
Channels in Kotlin are quite similar to Java’s BlockingQueue
, but with a key difference: channels suspend a coroutine rather than blocking a thread, making it a more efficient alternative.
First, let’s see how we can create a new channel:
runBlocking {
val chan = Channel<Int>()
...
}
Channels are type-specific. For example, this channel can only hold integers.
Next, let’s spawn a coroutine to read from the channel:
runBlocking {
...
...