Skip to content
Go back

How Kotlin Flow Works Internally — Upstream, Downstream, and the Operator Chain

Kotlin Flow Internals: Upstream, Downstream and Operator Chain

Kotlin Flow can feel like a black box. You chain operators, call .collect, and data appears. But the internal structure is straightforward — and once you see it, every operator and every rule about Flow becomes predictable.


The Problem Flow Solves

Before Flow, handling multiple async operations in sequence required nested callbacks:

getUser { user ->
    getProfile(user.id) { profile ->
        getSettings(user.id) { settings ->
            // finally do something
        }
    }
}

This is callback hell. Flow eliminates it by turning the chain into a linear pipeline where data moves from one step to the next — readable, cancellable, and testable.


Two Interfaces at the Core

Flow is built on two simple ideas. To understand them, imagine building your own Flow from scratch.

You need two interfaces:

fun interface Function {
    fun apply(value: String): String
}

fun interface Collector {
    fun collect(value: String)
}

Function takes a value, transforms it, and returns a new value. Collector takes a value and does something with it — log it, show it in the UI, save it. That is all.

Now build the Flow class around these:

class Flow(private var value: String) {

    fun map(fn: Function): Flow {
        value = fn.apply(value)
        return this                  // returns the same Flow — enables chaining
    }

    fun collect(collector: Collector) {
        collector.collect(value)     // terminal — no return
    }
}

Two things to notice:

The Kotlin Flow API in coroutines is built on these same ideas — just with generics, coroutine context, and suspend functions added.


Upstream and Downstream

These terms appear in every Flow discussion. They have a simple meaning:

Upstream is everything above the current point. Downstream is everything below it.

Flow("Amit")                         // ← source (upstream of everything)
    .map { mapToFullName(it) }       // ← downstream of source, upstream of next map
    .map { mapToUserName(it) }       // ← downstream of first map, upstream of collect
    .collect { Log.d(TAG, it) }      // ← downstream of everything (terminal)

Data flows strictly top to bottom — from source to collector. An operator never reaches back up. It receives data from above and passes transformed data below.

At every point in the chain, you can say: “everything above me is my upstream, everything below me is my downstream.”


SAM Interfaces: Why Lambdas Work

Both Function and Collector are declared with fun interface. This makes them SAM — Single Abstract Method — interfaces. A SAM interface has exactly one method.

Kotlin has a rule: if an interface has exactly one method, you can implement it with a lambda instead of a full anonymous class.

// Without SAM — verbose
.collect(object : Collector {
    override fun collect(value: String) {
        Log.d(TAG, value)
    }
})

// With SAM — clean lambda
.collect { Log.d(TAG, it) }

Both are identical at runtime. The lambda version is what the Kotlin compiler generates the anonymous class from. This is why Flow operators accept trailing lambdas — every operator interface is a SAM.

If an interface had two methods, a single lambda would be ambiguous. The SAM rule breaks down and you must provide a full implementation.


collect Is the Terminal Operator

A critical rule: nothing in a Flow runs until you call .collect.

val flow = Flow("Amit")
    .map { mapToFullName(it) }
    .map { mapToUserName(it) }

// At this point, zero code has executed inside the operators.
// The maps have not run. The value has not been transformed.

flow.collect { Log.d(TAG, it) }  // NOW the operators run

This is called a cold Flow. The pipeline is just a description of work until a terminal operator triggers it. If you build a Flow and never call .collect, the body of every operator is dead code.

In the Kotlin Flow API, .collect is a suspend function — which is why you always call it inside a coroutine scope:

lifecycleScope.launch {
    myFlow.collect { value ->
        // handle each emitted value
    }
}

Single vs Multiple Emissions

A Flow can emit one value or many. The two cases are distinct:

Single emission — a network call that returns a list:

flow {
    val users = api.getUsers()   // network call
    emit(users)                  // emits once — the whole list is one value
}

Even if users contains 100 items, this Flow emits exactly once. The list is one value.

Multiple emissions — a WebSocket that delivers messages over time:

flow {
    socket.messages.forEach { message ->
        emit(message)            // emits once per message — many times
    }
}

Each message is a separate emission. The collector is called once per emission, in order.

This distinction matters for how you write the collector:

.collect { value ->
    // called once for single-emission Flow
    // called N times for multi-emission Flow — once per emit
}

Chaining Operators: The Translation Analogy

Operators are most useful when a direct transformation is not possible and you need intermediate steps. Suppose you receive data in English but need to display it in Hindi — and there is no direct English-to-Hindi translator in your system:

Flow(englishData)
    .map { translateToSanskrit(it) }    // English → Sanskrit (step 1)
    .map { translateToHindi(it) }       // Sanskrit → Hindi (step 2)
    .collect { displayInUI(it) }        // terminal

Each .map call returns the same Flow object with the transformed value. You can chain as many operators as needed — two, three, ten. The return type of map being Flow is what makes this possible.

The key insight: Flow does not implement the transformation logic. It provides the structure and the API. The logic inside each lambda is entirely your code.


Summary

ConceptBehaviour
mapTransforms a value and returns the same Flow for chaining
collectTerminal operator — triggers execution and delivers the result
SAM interfaceOne-method interface → implementable as a lambda in Kotlin
Cold FlowNothing executes until .collect is called
UpstreamEverything above the current operator in the chain
DownstreamEverything below the current operator
Single emissionemit() called once (e.g. network call returning a list)
Multiple emissionsemit() called repeatedly (e.g. WebSocket messages)

The next post covers thread control in Flow — how flowOn works as a bridge, what operators run on which thread, and the most common mistake developers make when they assume IO work runs on the IO thread.


Share this post on:

Previous Post
flowOn: How Kotlin Flow Controls Which Thread Your Operators Run On
Next Post
Master Linux — Essential Commands Every Developer Uses in Production