Kotlin Expert · Lesson 1 · On the house

Channels

Channel, send/receive, produce; rendezvous vs buffered. Lesson 1 is free — on the house.

Lessons · Kotlin Expert · Lesson 1 of 10 · On the house

Channels

Channel, send/receive, produce; rendezvous vs buffered.

Illustration for Kotlin
Lesson 1 is on the house.

A Channel<T> is a hot communication pipe between coroutines: producers send values, consumers receive them. Unlike cold Flow, the channel exists independently of a single collector.

Channel() with no capacity is a rendezvous channel: send suspends until a receiver is ready, and receive suspends until a sender is ready. Channel(capacity) buffers that many elements before send suspends.

produce { send(1); send(2) } is a builder that returns a ReceiveChannel and closes it when the block finishes. Consume with receive(), for (x in channel), or consumeEach. Closing signals end-of-stream; receiving after close throws ClosedReceiveChannelException unless you use receiveCatching.

Prefer structured builders (produce inside a scope) over bare unbounded channels that outlive their owners. Cancel the producer job to stop work; unfinished buffered values may still be drained by the consumer.

Misses: treating Channel like cold Flow (it is hot), forgetting to close so consumers hang forever, or using Channel.UNLIMITED without a backpressure story.

channels

import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*

fun main() = runBlocking {
    val rendezvous = Channel<Int>()
    launch {
        rendezvous.send(1)
        rendezvous.send(2)
        rendezvous.close()
    }
    println(rendezvous.receive())
    println(rendezvous.receive())

    val produced = produce {
        send("a")
        send("b")
    }
    for (v in produced) println(v)
}
Match this when you type.

Quiz

What is Channel() with no capacity?

Quiz

What does produce { } return?

Quiz

How do you signal end-of-stream on a Channel?

Quiz

How does Channel differ from cold Flow?

Check

Match the still for: Channels.

Open-book: the answers are on this page. Pass every quiz and check (5) to mark the lesson done. This visit: 0/5.