Kotlin

Channel — Coroutine Communication

admin by @admin ADMIN
Jun 18, 2026
Jun 1, 2026
Public
0 0 up · 0 down Sign in to vote
A `Channel<T>` is a coroutine-safe queue — producer side sends, consumer side receives. Bounded buffer applies backpressure. Use Flow when broadcasting; use Channel for hand-off between coroutines.
Kotlin
Raw
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*

fun main() = runBlocking {
    val ch = Channel<Int>(capacity = 10)

    // Producer
    launch {
        for (i in 1..5) {
            ch.send(i)
            println("produced $i")
        }
        ch.close()                              // signal "no more" to consumer
    }

    // Consumer — `for` over a channel terminates when closed
    launch {
        for (item in ch) {
            println("consumed $item")
            delay(50)
        }
        println("channel closed")
    }
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.