DEV Community

Cover image for One Pipe, Three Faucets: How Flow Operator Fusion Collapses buffer(), conflate() and flowOn() Into…
Android Expert
Android Expert

Posted on Originally published at Medium

One Pipe, Three Faucets: How Flow Operator Fusion Collapses buffer(), conflate() and flowOn() Into…

One Pipe, Three Faucets: How Flow Operator Fusion Collapses buffer(), conflate() and flowOn() Into a Single Channel

You write three operators, you expect three stages. In kotlinx.coroutines, for a specific family of operators, you get one. That is a feature, and it is also the source of some of the quietest bugs I have seen in production Android code: buffers that silently vanish, sensor samples that never arrive, and flowOn calls that don't actually move anything anywhere.

This post walks through what fusion does, how the merge rules work, where it stops, and the failure modes that follow. The running example is a fictional hiking app, TrailPulse, that streams barometer readings to compute altitude gain.

🧠 TL;DR (Too Long; Didn’t Read)

  • buffer(), conflate() and flowOn() all return a fusible flow. Adjacent ones are merged into one configuration, and at most one channel is created when collection starts. A bare flowOn that doesn't change the dispatcher creates none.
  • Merging is not “last write wins” and not “sum everything”. The rules differ for suspending and non-suspending overflow policies.
  • flowOn allocates no channel at all when nothing else is fused in and the dispatcher doesn't change.
  • A plain operator such as map between two channel operators breaks fusion. Each side then gets its own configuration, and its own channel wherever one is actually needed.

fusion-myth-vs-reality

The setup that misleads

Here is the pipeline as I found it in a code review:

fun altitudeUpdates(barometer: Flow<Float>): Flow<Altitude> =
    barometer
        .buffer(64)
        .conflate()
        .flowOn(Dispatchers.Default)
        .map { hPa -> Altitude.fromPressure(hPa) }
Enter fullscreen mode Exit fullscreen mode

The author’s mental model: a 64-element buffer, then a conflating stage that protects the UI from bursts, then a hop to Default. In reality there is one conflated channel of a single slot. The 64 is gone.

Anatomy of fusion

Three types matter:

  • FusibleFlow is a flow that can absorb a later buffer, conflate or flowOn call. It doesn't mutate itself: its fuse function returns a new flow carrying the merged configuration.
  • ChannelFlow is the base of channelFlow {} and callbackFlow {}. It holds a CoroutineContext, a capacity, and a BufferOverflow policy.
  • ChannelFlowOperator wraps an arbitrary upstream flow so that buffer() and flowOn() have somewhere to store their configuration.

When you call buffer(), conflate() or flowOn() on a flow that is already fusible, the library does not stack a new stage. It asks the existing one for a rewritten copy of itself. The rewrite is the only thing that matters, so here is a simplified model of it. This is my own re-derivation for illustration, not the library source:

// Excerpt: imports are partly omitted, and `ChannelPlan` is a stand-in type, not a library class.
import kotlin.coroutines.CoroutineContext
import kotlinx.coroutines.channels.BufferOverflow
import kotlinx.coroutines.channels.Channel

private const val BUFFERED = Channel.BUFFERED            // -2: "use the default size"
private const val OPTIONAL = -3                          // "no channel needed unless someone asks"

data class ChannelPlan(
    val context: CoroutineContext,
    val capacity: Int,
    val overflow: BufferOverflow,
)

fun ChannelPlan.fuse(
    newContext: CoroutineContext,
    newCapacity: Int,
    newOverflow: BufferOverflow,
): ChannelPlan {
    // Earlier (upstream) context elements win ties, because `+` keeps the right-hand side.
    val mergedContext = newContext + context

    // By the time fusion runs, conflate() has already been translated by Flow.buffer into
    // (capacity = 0, DROP_OLDEST); the CONFLATED sentinel (-1) never reaches this function.
    // A policy that never suspends replaces whatever came before it.
    if (newOverflow != BufferOverflow.SUSPEND) {
        return ChannelPlan(mergedContext, newCapacity, newOverflow)
    }

    val mergedCapacity = when {
        capacity == OPTIONAL -> newCapacity
        newCapacity == OPTIONAL -> capacity
        capacity == BUFFERED -> newCapacity
        newCapacity == BUFFERED -> capacity
        else -> (capacity + newCapacity).let { if (it < 0) Channel.UNLIMITED else it }
    }
    return ChannelPlan(mergedContext, mergedCapacity, overflow)   // earlier policy is kept
}
Enter fullscreen mode Exit fullscreen mode

Two details are worth highlighting.

  1. conflate() is sugar. It calls buffer(Channel.CONFLATED), and buffer immediately rewrites that sentinel to "capacity 0 with DROP_OLDEST" before fusion. The channel factory then turns a zero-capacity, non-suspending channel into a one-slot conflated channel.
  2. Capacity has sentinel values. “Default buffer” (BUFFERED, which resolves to 64 unless overridden by a system property) and "no buffer requested" (an internal marker used by a bare flowOn) behave as placeholders during merging, not as numbers.

The merge rules, in one picture

fusion-merge-rules

The rows that bite are the third and fourth. They are mirror images of each other with different results:

// 64 is discarded: one slot, DROP_OLDEST.
flow.buffer(64).conflate()

// Capacity 64, DROP_OLDEST. Order flipped, behavior flipped.
flow.conflate().buffer(64)
Enter fullscreen mode Exit fullscreen mode

If you actually want “a bounded queue that drops the oldest entry when full”, say so directly instead of relying on the order of two operators:

flow.buffer(capacity = 64, onBufferOverflow = BufferOverflow.DROP_OLDEST)
Enter fullscreen mode Exit fullscreen mode

flowOn has a fast path that skips the channel entirely

The previous section is about what the channel looks like. A different question is whether a channel gets created at all. For a flowOn that has nothing fused into it, collection takes one of three routes before falling back to a channel:

flowon-collect-paths

This has a practical consequence that surprises people. A flowOn whose dispatcher matches the collector's gives you no concurrency:

// Collector runs on Dispatchers.Default; so does the upstream.
scope.launch(Dispatchers.Default) {
    repository.readings()
        .flowOn(Dispatchers.Default)   // no channel, no overlap: producer and consumer alternate
        .collect(::process)
}
Enter fullscreen mode Exit fullscreen mode

If the intent was to let the producer run ahead of a slow consumer, add .buffer() explicitly. That forces a real channel and a producer coroutine.

One more thing to watch on Android: Dispatchers.Main and Dispatchers.Main.immediate are different dispatchers for the "same dispatcher" comparison, as far as I can tell from the source. A flowOn(Dispatchers.Main) inside viewModelScope therefore appears to pay for a channel that flowOn(Dispatchers.Main.immediate) would avoid. Confirm with a trace on your version before changing anything.

Where fusion stops

Fusion only merges neighbours. A plain operator like map, filter or onEach is not a channel operator, so it ends the run:

fusion-breakers

// One channel: conflate and flowOn are adjacent.
barometer.conflate().flowOn(Dispatchers.IO)

// Two channels: map sits between the flowOn calls.
barometer
    .flowOn(Dispatchers.IO)
    .map { smooth(it) }
    .flowOn(Dispatchers.Default)
Enter fullscreen mode Exit fullscreen mode

Related: two stacked flowOn calls with no operator between them fuse, and the upstream one wins on conflicts. flow.flowOn(Dispatchers.Default).flowOn(Dispatchers.IO) runs the producer on Default. This matters when a repository applies flowOn(IO) and a caller later applies its own. The caller's dispatcher is not what you get.

Real-world failure modes

1. The disappearing buffer

Already shown: buffer(n).conflate() is a one-slot conflated channel. It is the most common source of "I sized this buffer but I still lose events" tickets.

2. callbackFlow and the silent trySend

callbackFlow is itself fusible, with a default suspending buffer of 64. Inside a listener you cannot suspend, so you call trySend. When the buffer is full, trySend returns a failure result and the newest sample is the one that is lost, usually with nobody checking the return value.

callbackflow-trysend-loss

fun SensorManager.pressureFlow(
    sensor: Sensor,
    samplingPeriodUs: Int = SensorManager.SENSOR_DELAY_UI,
): Flow<Float> = callbackFlow {
    val listener = object : SensorEventListener {
        override fun onSensorChanged(event: SensorEvent) {
            trySend(event.values[0])          // copy the float; the array is reused by the system
        }
        override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) = Unit
    }
    val registered = registerListener(listener, sensor, samplingPeriodUs)
    if (!registered) {
        // Fail fast instead of suspending forever in awaitClose with no listener attached.
        close(IllegalStateException("Could not register listener for sensor ${sensor.name}"))
    }
    awaitClose { unregisterListener(listener) }
}.conflate()                                   // fused into the builder's own channel
Enter fullscreen mode Exit fullscreen mode

For state-like signals (pressure, location, battery level) the freshest value is the one you want. conflate() here adds no extra hop, and trySend can no longer fail for lack of space. It can still return a closed failure if the collector cancels while a callback is in flight, which is harmless here because awaitClose unregisters the listener. Also make sure the flow is collected from a lifecycle-aware scope (for example with repeatOnLifecycle), otherwise the sensor stays registered.

3. Conflating things that are events, not state

conflate() drops intermediate values by design. Pair it with a stateful operator and you get wrong answers, not just fewer answers:

// Counts only the clicks that survived conflation.
clicks.conflate().scan(0) { count, _ -> count + 1 }
Enter fullscreen mode Exit fullscreen mode

Rule: conflate state, never events.

4. Where you put conflate() relative to map

// Smoothing runs on the collector side and only sees the latest value.
readings.conflate().map { expensiveSmoothing(it) }

// Smoothing runs on the producer side and sees every reading; conflation happens afterwards.
readings.map { expensiveSmoothing(it) }.conflate()
Enter fullscreen mode Exit fullscreen mode

The first is right if the work is idempotent and you only care about the latest result. The second is required if the operator carries state (a filter window, a Kalman estimate) that needs every sample.

5. A default buffer of 64 holding heavy payloads

buffer() with no arguments keeps up to 64 elements. For small values that is nothing. For camera frames or decoded bitmaps it can become a real memory spike on a slow device; profile it with your actual payload before deciding. (Camera ImageProxy objects also need an explicit close(), which buffering makes easy to get wrong.) Use buffer(1, BufferOverflow.DROP_OLDEST) or conflate() for large, replaceable payloads.

6. flowOn that doesn't change threads

Covered above: same dispatcher means no channel and no parallelism. Don’t rely on flowOn as a "make this concurrent" switch.

7. Redundant operators before sharing

StateFlow is conflated by definition. A conflate() before stateIn is redundant, and a flowOn before stateIn or shareIn mainly decides the context the sharing coroutine runs the upstream in. Don't count on extra channels being built for you here either.

Performance: what fusion actually saves

Each real channel boundary costs you, per collection:

  • a producer coroutine (a Job plus continuation objects),
  • the channel and its buffer segments,
  • a dispatch to another thread (or at least another scheduling turn) for each handoff, with the cache and visibility costs that come with it.

For low-frequency flows, such as taps or navigation events, none of this is measurable. For streams at sensor, audio or scroll rates, it can be the difference between a hot path that allocates per element and one that doesn’t. Confirm with an allocation trace on your target hardware. I’m deliberately not quoting numbers: they depend heavily on device, dispatcher and element rate. Measure on a representative low-end device, using custom Trace.beginSection markers and a Macrobenchmark, and compare the fused and unfused variants of the same pipeline.

The practical guidance:

  1. Put channel operators next to each other so they fuse.
  2. Don’t insert a map between two flowOn calls unless you want two producers.
  3. Prefer one explicit buffer(capacity, overflow) over relying on operator order.

Verifying fusion instead of trusting it

Inspect the configuration. Printing a fused flow shows its capacity and overflow policy. The exact format is not a stable contract, so use it as a debugging aid only:

val pipeline = flowOf(1).buffer(64).conflate().flowOn(Dispatchers.Default)
println(pipeline) // expect one operator node mentioning capacity=0 and DROP_OLDEST
Enter fullscreen mode Exit fullscreen mode

Pin the behavior in a test. Under runTest, coroutines that all run on the same test scheduler are scheduled deterministically, so the outcome is repeatable. That holds only while no real dispatcher (Dispatchers.IO or Default) enters the pipeline; add a flowOn to one of those and the interleaving becomes timing-dependent. A conflated pipeline with a slow collector delivers the first value and the latest one:

@Test
fun `buffer size is discarded when conflate follows`() = runTest {
    val received = mutableListOf<Int>()

    (1..5).asFlow()
        .buffer(64)
        .conflate()
        .collect { value ->
            received += value
            delay(100)
        }

    // With buffer(64) alone this would be [1, 2, 3, 4, 5].
    assertEquals(listOf(1, 5), received)
}
Enter fullscreen mode Exit fullscreen mode

If a library upgrade ever changes the merge semantics, this is the test that tells you before your users do.

Checklist

  • Do I know how many channels this chain creates? (Count the plain operators between channel operators.)
  • Is every buffer(n) actually followed by something that preserves n?
  • Are callbackFlow and channelFlow sources conflated, or sized deliberately?
  • Am I conflating state or events?
  • Does my flowOn change the dispatcher, or is it a no-op?
  • Is a heavy payload sitting in a default-sized buffer?

📱 Go Beyond Using Jetpack Compose

If you’re building on Android, understanding what happens under the hood separates developers who use Compose from those who master it. I highly recommend “Mastering Jetpack Compose Internals”. It’s a deep, architecture-first walkthrough of the composition tree, the slot table, snapshot state, and the runtime that powers modern Android UI — capped off with a full case study building a real app called Mosaic.

Top comments (0)