Channels
Explore how channels in Kotlin enable communication between coroutines by suspending rather than blocking execution. Understand creating typed channels, sending and receiving data, and using producers and actors. Learn about buffered channels to decouple producers from consumers and improve concurrency management.
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 ...