Careeroza
Channel Basics
A Queue Between Coroutines
A Channel<T> is like a BlockingQueue for coroutines: one coroutine sends, another receives. Both are suspend functions, so nothing blocks a thread. Unlike a flow, a channel is hot and each value is received by exactly one receiver.
producer ──send()──► [ channel ] ──receive()──► consumer
Example
Example
close() tells the receiver no more values will come; the for loop then ends.
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
fun main() = runBlocking {
val orders = Channel<String>()
launch {
for (dish in listOf("Pizza", "Burger", "Biryani")) {
println("Kitchen sends $dish")
orders.send(dish)
}
orders.close()
}
for (order in orders) {
println("Rider picks $order")
}
println("No more orders")
}Output
Kitchen sends Pizza Kitchen sends Burger Rider picks Pizza Rider picks Burger Kitchen sends Biryani Rider picks Biryani No more orders
Channel API
| Function | Does |
|---|---|
send(x) | suspends if the buffer is full |
receive() | suspends until a value arrives; throws if closed |
trySend(x) / tryReceive() | non-suspending versions, return a result object |
receiveCatching() | like receive, but returns a closed result instead of throwing |
close() | no more sends; remaining values can still be received |
for (x in channel) / consumeEach | receive until closed |