Skip to content
Tutorials Center
My learning

Topics

Lesson 100 of 134 ยท Coroutines

Channels

Learn Kotlin coroutine channels - send and receive, rendezvous and buffered channels, close and for loops, produce, conflated channels, fan-out, fan-in and pipelines, with runnable examples.

Coroutines started with launch and async are good at doing work, but how do they talk to each other? You could share a mutable variable, but then you need locks (see shared mutable state). Kotlin offers a safer model: channels. A channel is a pipe. One coroutine puts values in with send, another takes them out with receive, and the pipe makes sure that each value arrives exactly once and that nobody has to wait with a thread.

A channel is like a BlockingQueue from Java, except that its send and receive are suspending functions: when the channel is full or empty, the coroutine pauses instead of blocking a thread. This lesson covers sending, closing, buffering, producers, and the two classic shapes, fan-out and fan-in. It comes after exceptions in coroutines, and it is followed by flows, which are the better choice for many streaming problems.

A first channel

Channel<T>() creates a channel for values of type T. A producer calls send(value), a consumer calls receive().

Kotlin Send and receive

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The consumer loop for (value in channel) receives until the channel is closed and empty, then ends. The producer and the consumer take turns: each send waits for the consumer to take the value. The exact interleaving of the sending and received lines depends on how the single thread schedules the two coroutines, but every value arrives in order, and the loop ends after close(). This is the default behavior of a rendezvous channel.

Rendezvous: no buffer at all

A channel created without arguments has capacity 0. send suspends until a receiver is ready, and receive suspends until a sender is ready. They meet ("rendezvous") and the value is handed over directly. This is a natural form of back-pressure: a fast producer cannot run far ahead of a slow consumer.

Kotlin Back-pressure on a rendezvous channel

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The producer suspends in the very first send for the full 100 ms, because nobody is receiving. Each producer: handed over line appears right after the matching consumer: got line, and the producer can move on to the next item only when the consumer asks again.

Closing a channel

A channel has two ends and a life cycle. close() says "no more values will be sent". Values already sent can still be received; after they are consumed, the receiving loop ends. Sending to a closed channel throws, and receive() on a closed and empty channel throws too:

Kotlin Using a closed channel (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

You see 1, 2 and true, then the program stops with kotlinx.coroutines.channels.ClosedSendChannelException: Channel was closed. For receiving, receiveCatching() returns a result you can inspect instead of throwing, and a loop is usually written as for (x in channel). A different tool is cancel(): it closes the channel and throws away all buffered values, for use when the consumer is no longer interested.

Somebody has to close the channel, or consumers waiting in a for loop wait forever. The usual rule: the producer closes, the consumer never does. produce (below) closes automatically.

Buffered channels

Give a capacity and the producer can run ahead by that many values before it suspends:

Kotlin A buffer of two

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The producer sent 1 and 2 into the buffer, then suspended while trying to send 3, before the consumer even started. When the consumer takes a value, space is freed and the producer continues.

The capacity options:

Capacity Meaning
Channel.RENDEZVOUS (0, the default) no buffer; sender and receiver meet
a number n buffer of n values; send suspends when full
Channel.UNLIMITED unbounded buffer; send never suspends (memory can grow without limit)
Channel.CONFLATED keeps only the latest value; send never suspends
Channel.BUFFERED a default-sized buffer (64 by default)

Conflated: only the latest matters

For things like "current temperature" or "latest search text", a slow consumer should skip old values and see only the newest. That is what CONFLATED does:

Kotlin A conflated channel

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The first four values were overwritten and only 5 arrived. tryReceive() is the non-suspending version of receive: it returns immediately with a result that is a failure if nothing is available. There is also trySend, which returns a failure instead of suspending when a bounded channel is full, so it is usable from non-suspending code such as callbacks.

Choosing the overflow behavior

Channel(capacity, onBufferOverflow = ...) makes the full-buffer behavior explicit: SUSPEND (default), DROP_OLDEST, or DROP_LATEST. CONFLATED is just a capacity of 1 with DROP_OLDEST. Use dropping behavior for telemetry or UI events where freshness beats completeness, and suspension when every value must be processed.

Kotlin Dropping the oldest values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Only the three newest values remain: [8, 9, 10]. A bounded channel with a clear overflow rule is the safest default for anything that can be produced faster than it is consumed.

produce: a producer coroutine

Writing "launch, send, close" over and over is noisy. produce { ... } starts a coroutine that returns a ReceiveChannel, with send available in the lambda, and closes the channel for you when the block ends, even when it fails. It is the preferred way to create a channel that has one producer.

Kotlin produce and consume

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

toList() and consumeEach { } read until the channel is closed. Convention: a function that starts a producer is an extension of CoroutineScope, so the caller's scope owns the coroutine; and it returns ReceiveChannel (read-only), so a consumer cannot send into it by mistake.

Pipelines

Because a channel is a value, producers can be chained: one stage reads from a channel and writes to another. This is a pipeline.

Kotlin A three-stage pipeline

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Each stage is a coroutine, so they run concurrently, and each rendezvous channel keeps them in step. Without the last cancelChildren() the program would never end, because numbers() is infinite. Remember that every stage of a pipeline is a coroutine to be cancelled.

Fan-out: many consumers, one channel

Several coroutines can receive from the same channel. Each value goes to exactly one of them, so the work is shared among workers. This is the pattern for a work queue.

Kotlin Workers sharing a queue

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Which worker took which job varies from run to run, so we sorted the results; every job was handled exactly once. Using for (job in jobs) instead of while (true) receive() is important here: it ends cleanly when the channel is closed, and, unlike consumeEach, it does not cancel the channel when one worker fails, so the other workers keep going.

Fan-in: many producers, one channel

The mirror image: several coroutines send into one channel, and a single consumer reads the merged stream.

Kotlin Merging producers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The consumer sees the items in the order they were produced in time. Here we know the total (6) and receive exactly that many; in real code, someone must close merged when all producers are done, often by waiting in a parent: launch { children.joinAll(); merged.close() }.

Channels vs. other tools

  • A channel delivers each value to one consumer and has no replay. It fits work queues and hand-over between coroutines.
  • A Flow is a cold stream: it starts when somebody collects it, and each collector gets all values. Prefer it for sequences of data that flow through transformations.
  • StateFlow and SharedFlow broadcast to many collectors.
  • For plain thread-based code, java.util.concurrent.BlockingQueue plays the same role as a channel, but blocks threads.

Channels are a lower-level building block than flows. In application code you will often use Flow, and use channels for work distribution, event buses between components, and as the machinery inside callbackFlow, channelFlow and produceIn.

Pitfalls

  • Forgotten close: consumers hang on a for loop forever. Close from the producer, or use produce.
  • Unlimited buffers: Channel.UNLIMITED hides slow consumers until memory runs out. Prefer a bound.
  • Sending from a blocked thread: send is a suspend function; call it from a coroutine, or use trySend from callbacks.
  • Two consumers expecting the same value: a channel is not a broadcast. Use SharedFlow for that.
  • Leaks after cancel: if the consumer stops early, cancel the channel (or the producer's scope), otherwise the producer stays suspended in send for good.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What happens when you call send on a rendezvous channel (capacity 0) and nobody is receiving?

    A rendezvous channel has no buffer; send suspends (without blocking a thread) until a receiver takes the value.
  2. 2. Which capacity keeps only the most recently sent value?

    CONFLATED overwrites the buffered value with the newest one, so send never suspends and a slow receiver sees only the latest.
  3. 3. Three workers all run for (job in jobs) on the same channel. How many workers receive a given job?

    A channel delivers each value to exactly one receiver, which makes it a work queue (fan-out).
  4. 4. What does produce { ... } do when its block finishes?

    produce closes the channel when the block completes or fails, so consumers' loops end.
  5. 5. A consumer's for (x in channel) loop never ends although all producers have finished. What is the most likely cause?

    The loop ends only when the channel is closed and empty; someone has to call close().

Summary

  • A Channel<T> passes values between coroutines with suspending send and receive; no thread is blocked.
  • The default capacity is rendezvous (0), which gives back-pressure; add a buffer, CONFLATED, or an overflow rule when needed.
  • Close the channel from the producer; for (x in channel) ends on close. Sending to a closed channel throws ClosedSendChannelException.
  • produce creates a producer coroutine that closes its channel for you; stages can be chained into pipelines.
  • Fan-out (many receivers) shares work, with each value delivered once; fan-in (many senders) merges streams.
  • trySend and tryReceive never suspend.

Next: Flows