Channels

Flow and StateFlow Senior Kotlin 2.0+ API 24+ Reviewed By Best Latest Apps

Predict the output

Two workers receive from the same channel. How many lines are printed in total?

fun main() = runBlocking {
    val jobs = Channel<Int>()
    repeat(2) { worker ->
        launch { for (j in jobs) println("w$worker got $j") }
    }
    for (i in 1..4) jobs.send(i)
    jobs.close()
}
Options
Hint 1 of 1

Can two receivers get the same element?

Choose an answer, then open Show answer below to check it.

Show answer

Answer: A 4: each job goes to one worker

Correct. A channel element is received by exactly one receiver.

Why not the others?
  • B 8: both workers get every job. That's SharedFlow behaviour, not a channel's.
  • C 2: each worker takes one job and stops. for (j in jobs) loops until the channel is closed.
  • D 0: send suspends forever. Workers are receiving, so each rendezvous send completes.

30-second answer

A Channel is a hot, concurrent queue between coroutines: send suspends when the buffer is full and receive suspends when it's empty. Each element is received by exactly one receiver. A Flow is a cold description of values. Channels are for handing work between coroutines; flows are for exposing streams.

Practise saying it · 30 s. No recording, just a timer

Explain Channel vs Flow.

Say your answer out loud, then check which of these points you covered:

  • Channel is a hot queue
  • Each element goes to one receiver
  • Flow is a cold stream
  • Close channels when done

Deep dive

Capacities: RENDEZVOUS (default, 0), BUFFERED, CONFLATED and UNLIMITED.

Close a channel when the sender is done; for (x in channel) ends after close.

receiveAsFlow() exposes a channel as a flow where each value still goes to one collector.

A worker pool: several coroutines receiving from one channel split the work between them.

Common mistakes

  • Exposing a Channel publicly instead of a Flow.
  • Never closing a channel, so receivers wait forever.
  • Expecting every receiver to get every element.

Senior take & follow-ups

Contrast 'one receiver per element' with SharedFlow's 'every collector gets it'.

Follow-up questions

Think of your answer first, then open the hint.

  1. What's the default channel capacity?

    Show hint

    Rendezvous: send waits until someone receives.

  2. How do you fan out work to three workers?

    Show hint

    Start three coroutines that each loop over the same channel.

Suggest a fix if something here is wrong or out of date.