Search⌘ K
AI Features

Channels as a Communication Primitive

Explore how channels function as a communication primitive in Kotlin coroutines to ensure safe and fair interaction between concurrent tasks. Learn to use channels with coroutine builders like produce, create pipelines to balance workloads, and apply buffering strategies to optimize processing—as seen in practical examples like managing online shop updates.

Channels are useful when different coroutines need to communicate with each other. They guarantee no conflicts (i.e., no problem with the shared state) and fairness.

To see them in action, imagine that different baristas are making coffees. Each barista should be a separate coroutine working independently. Different coffee types take different amounts of time to prepare, but we want to handle orders in the order they appear. The easiest way to solve this problem is by sending both the orders and the resulting coffees in channels. A barista can be defined using the produce builder.

Kotlin 1.5
suspend fun CoroutineScope.serveOrders(
orders: ReceiveChannel<Order>,
baristaName: String
): ReceiveChannel<CoffeeResult> = produce {
for (order in orders) {
val coffee = prepareCoffee(order.type)
send(
CoffeeResult(
coffee = coffee,
customer = order.customer,
baristaName = baristaName
)
)
}
}
...