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()andflowOn()all return a fusible flow. Adjacent ones are merged into one configuration, and at most one channel is created when collection starts. A bareflowOnthat 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.
-
flowOnallocates no channel at all when nothing else is fused in and the dispatcher doesn't change. - A plain operator such as
mapbetween two channel operators breaks fusion. Each side then gets its own configuration, and its own channel wherever one is actually needed.
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) }
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:
-
FusibleFlowis a flow that can absorb a laterbuffer,conflateorflowOncall. It doesn't mutate itself: itsfusefunction returns a new flow carrying the merged configuration. -
ChannelFlowis the base ofchannelFlow {}andcallbackFlow {}. It holds aCoroutineContext, a capacity, and aBufferOverflowpolicy. -
ChannelFlowOperatorwraps an arbitrary upstream flow so thatbuffer()andflowOn()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
}
Two details are worth highlighting.
-
conflate()is sugar. It callsbuffer(Channel.CONFLATED), andbufferimmediately rewrites that sentinel to "capacity 0 withDROP_OLDEST" before fusion. The channel factory then turns a zero-capacity, non-suspending channel into a one-slot conflated channel. -
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 bareflowOn) behave as placeholders during merging, not as numbers.
The merge rules, in one picture
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)
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)
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:
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)
}
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:
// 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)
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.
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
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 }
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()
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
Jobplus 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:
- Put channel operators next to each other so they fuse.
- Don’t insert a
mapbetween twoflowOncalls unless you want two producers. - 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
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)
}
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 preservesn? - Are
callbackFlowandchannelFlowsources conflated, or sized deliberately? - Am I conflating state or events?
- Does my
flowOnchange 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.
- E-book: Available on Google Play
- Kindle Edition: Available on Amazon
- Topmate: Available on Topmate
- Also available in Paperback & Hardcover





Top comments (0)