Flow: Cold Asynchronous Streams

Flow: Cold Asynchronous Streams in Kotlin: --- A village square has a cast-iron hand pump standing over a deep well.


The Analogy: The Village Hand Pump Over a Well

A village square has a cast-iron hand pump standing over a deep well. Unlike a tap fed by a pressurised main, the pump holds no standing water in its spout. Until somebody actually works the handle, not a single drop moves. The water is all down in the well; the pump is merely the mechanism that will draw it up, on demand, whenever it is worked. A pump left untouched all day has produced nothing, and that is not a fault -- it is simply what a pump is.

Working the handle draws water one stroke at a time. Each down-stroke lifts one measure to the spout, and the pump never races ahead to pile water on the ground faster than the person can catch it. It produces exactly as fast as someone pumps and fills their bucket; if they pause with the bucket half full, the pump simply waits, the rest of the water still resting in the well, until the next stroke. The rate is set by the person taking the water, not by the source. The taker pulls; the source does not push.

Beside the pump sits a row of screw-on filters -- a grit screen, a charcoal cartridge. A villager can thread these onto the spout in advance, arranging exactly how the water should be treated on its way out, but threading a filter draws no water by itself; the filters only do their work on water that is actually being pumped through them. And when the next villager arrives with their own bucket, they begin their own pumping from scratch. The pump remembers nothing of the previous person's water; every drawer of water gets a fresh, independent draw from the same well, treated by whatever filters they chose to fit.

The wasted trip is the villager who carefully threads on every filter, stands back to admire the arrangement, and then walks away without ever working the handle. They carry home an empty bucket, because a pump that is never worked yields nothing no matter how cleverly it is configured. The opposite error is assuming the spout is a pressurised tap with water already standing in it, ready to gush the instant it is touched. Treat a hand pump that way and you will stand there puzzled when nothing comes, because the water arrives only when you pump. Arranging the mechanism is never the same act as drawing the water.


Syntax or Core Structure

A Flow is a cold asynchronous stream: it describes how to produce a sequence of values, but produces nothing until a terminal operator such as collect works the handle. You build one with the flow { } builder, emitting values with emit. The builder block does not run when the flow is created -- only when it is collected.

import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*

fun numbers(): Flow<Int> = flow {
    println("pump starts drawing")
    for (n in 1..3) {
        delay(10L)
        emit(n)
    }
}

fun main() = runBlocking {
    val f = numbers()                 // nothing drawn yet
    println("flow built, not collected")
    f.collect { value -> println("caught " + value) }
    println("done")
}

Output:

flow built, not collected
pump starts drawing
caught 1
caught 2
caught 3
done

The call numbers() returns a Flow without running a line of its builder, so "flow built, not collected" prints first -- the filters are threaded on, but no water has moved. Only when collect works the handle does the builder run: "pump starts drawing" prints, then each emit delivers a value to the collect block, which prints "caught 1", "caught 2", "caught 3" in emit order. When the builder finishes, collect returns and "done" prints. The lambda passed to collect is the bucket under the spout, receiving one measure per stroke. Building the flow and collecting it are two separate acts, and nothing is produced until the second one.


Technical Depth: Operators, Coldness, and Short-Circuiting

Intermediate operators are screw-on filters; terminals work the handle

Operators on a flow fall into two families. Intermediate operators (map, filter, take, onEach) return a new Flow and run nothing -- they screw another filter onto the spout and hand the assembly back. Terminal operators (collect, toList, first, count, reduce) are the ones that actually work the handle: they are suspend functions that start the upstream producer and pull values through every filter.

OperatorFamilyReturnsRuns the producer?
mapintermediateFlow<R>no
filterintermediateFlow<T>no
take(n)intermediateFlow<T>no
onEachintermediateFlow<T>no
collectterminalUnityes
toListterminalList<T>yes
firstterminalTyes
countterminalIntyes

Because intermediate operators only build a new description, a chain like numbers().filter { it % 2 == 1 }.map { it * it } produces nothing on its own. It is inert plumbing until a terminal pulls on it.

import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*

fun main() = runBlocking {
    val oddSquares = (1..5).asFlow()
        .filter { it % 2 == 1 }
        .map { it * it }
    println("chain built")
    val result = oddSquares.toList()
    println("result " + result)
}

Output:

chain built
result [1, 9, 25]

"chain built" prints before any value flows, proving filter and map did no work at construction time. Only toList -- a terminal -- pulls values through: 1, 3, 5 survive the filter, then square to 1, 9, 25, collected in order into the returned list.

A cold flow re-runs its producer for every terminal

Cold means each terminal operator starts the producer from scratch, exactly as each person at the pump draws fresh water. Collect the same flow twice and the builder block runs twice.

import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*

fun main() = runBlocking {
    val f = flow {
        println("opening source")
        emit(1)
        emit(2)
    }
    f.collect { println("A got " + it) }
    f.collect { println("B got " + it) }
}

Output:

opening source
A got 1
A got 2
opening source
B got 1
B got 2

"opening source" prints twice because each collect is an independent draw. There is no shared buffer, no replay of a single run -- the flow is a recipe, not a filled bucket. This is the defining trait of a cold stream and the single most common source of surprise: any expensive setup inside the builder happens once per collector, not once per flow.

take short-circuits and cancels the producer

The take(n) operator stops collection after n values and cancels the upstream producer, so the builder does not run to completion.

import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*

fun main() = runBlocking {
    val f = flow {
        for (n in 1..100) {
            println("producing " + n)
            emit(n)
        }
    }
    val taken = f.take(2).toList()
    println("taken " + taken)
}

Output:

producing 1
producing 2
taken [1, 2]

The producer prints "producing 1" and "producing 2", then take(2) has its quota and cancels upstream before the loop reaches 3 -- the remaining 98 iterations never run. The collected list is [1, 2], rendered by the default list toString. Short-circuiting turns an unbounded producer into a bounded pull without any special cooperation from the builder.


Real World Example: A Sensor Reporting Pipeline

Consider a small monitoring job that reads a batch of temperature samples from a sensor and prints a report: how many readings sit at or above a warning threshold, the full list of readings, and their average. The sensor is modelled as a cold flow whose builder prints "opening sensor" so we can see exactly when it is engaged.

import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*

fun sensorReadings(): Flow<Int> = flow {
    println("opening sensor")
    val samples = listOf(18, 21, 19, 24, 22)
    for (s in samples) {
        delay(5L)
        emit(s)
    }
}

suspend fun report(threshold: Int) {
    val readings = sensorReadings()
    val warm = readings.filter { it >= threshold }.count()
    val all = readings.toList()
    val average = all.sum() / all.size
    println("count at or above " + threshold + ": " + warm)
    println("all readings: " + all)
    println("average: " + average)
}

fun main() = runBlocking {
    report(21)
}

Output:

opening sensor
opening sensor
count at or above 21: 3
all readings: [18, 21, 19, 24, 22]
average: 20

The report is correct on the numbers. The count terminal pulls the five samples through the filter, keeping 21, 24, and 22, so warm is 3. The toList terminal collects all five into [18, 21, 19, 24, 22]; their sum is 104 and integer division by 5 gives an average of 20. The threshold parameter is genuinely read by the filter, and both aggregates -- the count and the list -- feed the printed lines.

Structuring the sensor as a cold flow keeps the reading logic in one place and lets the caller compose filters without the sensor knowing anything about thresholds. The count operator short-circuits nothing here but does stream the values one at a time rather than buffering, which matters when a real sensor emits thousands of samples. Modelling I/O as a flow also means cancellation and timeouts from the surrounding coroutine apply for free: wrap report in withTimeout and a hung sensor read is abandoned at the next suspension point.

The design flaw is written plainly in the output: "opening sensor" prints twice. Because a cold flow re-runs its producer for every terminal operator, and report applies two terminals -- count and toList -- to the same readings flow, the sensor is opened and read from scratch twice for a single report. Here the samples are hard-coded so both passes agree, but a real sensor could return different values on the second read, making warm and all mutually inconsistent, and the second physical read is pure waste. The fix is to work the handle once: val all = readings.toList() first, then derive the count from that in-memory list with all.count { it >= threshold }. One draw, one consistent snapshot.

Common Mistakes

  1. Building a flow and never collecting it. Because intermediate operators run nothing, a chain like sensorReadings().filter { it > 20 } that is assigned and then dropped does no work at all. If you expected side effects, they never happened -- you threaded the filters but never worked the handle.
  1. Assuming the producer runs once per flow. A cold flow re-runs its builder for every terminal. Collecting the same flow in two places, or applying count and toList to one flow, opens the source twice. Snapshot once with toList if you need several aggregates.
  1. Doing expensive setup inside the builder for a multi-collected flow. Opening a file or a network connection at the top of flow { } repeats that cost on every collection. Move one-time setup outside, or convert to a hot flow with shareIn/stateIn when a single upstream should feed many collectors.
  1. Calling a blocking function directly inside flow { }. The flow builder runs in the collector's coroutine; a blocking call there stalls that coroutine and can deadlock. Use flowOn(Dispatchers.IO) to move the upstream to an appropriate dispatcher instead of blocking the collector.
  1. Emitting from a different coroutine than the builder's. emit is not thread-safe across coroutines; launching a child inside flow { } and emitting from it throws IllegalStateException. Use the channelFlow builder when emissions genuinely originate from concurrent sources.
  1. Expecting collect to return before the flow completes. collect is a suspend function that resumes only after the last value (or an exception). Code written after collect runs when the stream is done, not concurrently with it -- launch the collection in its own coroutine if you need overlap.
  1. Swallowing upstream exceptions with a try/catch around emit. Wrapping emit in a try/catch can catch downstream failures and violate flow's exception transparency. Handle errors with the catch operator, which only sees exceptions from upstream.
  1. Assuming take leaves the producer running. take(n) cancels upstream once satisfied, so a builder's cleanup after the emit loop may never run. Put cleanup in onCompletion or a finally, which fire even when collection is cancelled early.
  1. Confusing a cold Flow with a hot StateFlow. A StateFlow always has a current value and shares one producer among all collectors; a Flow has neither trait. Reaching for a plain flow where you need a current-value-plus-updates model leads to missed initial state and duplicated work.

Best Practices

  • Keep flow builders free of side effects beyond emit, so that re-running the producer on each collection is safe and predictable.
  • Snapshot with toList once when you need multiple aggregates from the same source, rather than applying several terminals to one cold flow.
  • Push upstream work onto the right dispatcher with flowOn instead of blocking inside the builder or switching context by hand.
  • Handle failures with the catch operator and cleanup with onCompletion, keeping exception handling out of the emit path.
  • Use channelFlow when values genuinely come from concurrent producers, and a plain flow when a single sequential builder suffices.
  • Reach for stateIn or shareIn to turn a cold flow hot when one expensive upstream should feed many collectors.
  • Prefer bounded terminals like first and take when you only need a prefix, letting the producer short-circuit instead of running to completion.
  • Name flows for the values they carry, not the mechanism, so call sites read as data streams rather than coroutine plumbing.

Practice Exercises

  1. Write a cold flow that emits the integers 1 through 5 with a small delay between each, then collect it twice in main. Add a println at the top of the builder and confirm from the output that the producer runs once per collection.
  1. Build a flow of words and chain filter (length greater than 3) and map (to uppercase) onto it. Print a line before the terminal operator to demonstrate that the intermediate operators do no work until toList is called.
  1. Take the sensor pipeline from the Real World Example and fix its double-open flaw: collect the readings into a list exactly once, then compute both the warning count and the average from that list. Verify "opening sensor" now prints a single time.
  1. Create an effectively unbounded flow that emits an incrementing counter in a loop, then use take(3) and toList to pull only the first three values. Add a println inside the loop and confirm the producer stops after three iterations rather than running forever.