liveBook · Manning

Channel flow

As explained in Kotlin in Action, 2E

channelFlow is a Kotlin coroutine builder that creates a cold flow supporting concurrent emissions from multiple coroutines.

A channel flow is a special cold flow built with channelFlow for concurrent emissions from multiple coroutines. Instead of emit, launched coroutines use send; collection still delivers values sequentially. section 16.2.5

Send values concurrently

val randomNumbers = channelFlow { repeat(10) { launch { send(getRandomNumber()) } } } The builder supplies a coroutine scope, so each launch can execute getRandomNumber concurrently. With ten 500-millisecond delays, the work finishes in roughly 500 milliseconds rather than running ten times sequentially. section 16.2.5

Choose channelFlow when concurrent producers are needed; otherwise prefer the simpler regular cold flow.

  • A regular cold flow restricts emit calls to one coroutine; launching background coroutines that emit directly violates the flow invariant. section 16.2.5
  • Regular cold flows remain the simplest and most performant option when sequential production is sufficient, because channel flows add concurrency and overhead. section 16.2.5

How Kotlin in Action, 2E covers it

How deep it goes
Explains the builder, send-based emission, coroutine launching, timing benefit, and tradeoff against regular cold flows.
Examples
Demonstrates ten delayed random-number producers launched concurrently inside channelFlow.
What it assumes
Assumes familiarity with Kotlin coroutines, cold flows, launch, emit, and collecting flow values.
What you can do after
Build concurrent Kotlin flows by launching coroutines inside channelFlow and sending values with send.
How it connects
Connects channel flows with cold flows, coroutines, FlowCollector, emit, send, and hot flows.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Kotlin in Action, 2E. The section links point to the parts of the book it draws on.