CodeGym /Courses /Kotlin SELF /Flow as a cold stream: flow { emit }, collect, and how it...

Flow as a cold stream: flow { emit }, collect, and how it differs from Channel

Kotlin SELF
Level 54, Lesson 2
Available

1. Introduction

When you first see Flow, your brain honestly asks: “Why do we need yet another thing if we already have Channel? We just learned how to send, receive, close— even enable buffering!” This is a normal reaction: programmers are generally inclined to think the world already has enough new entities, especially on Monday morning.

The difference is what exactly you are modeling. Channel is, first and foremost, communication: coroutines “toss” values to each other like a ball. And Flow is an description of the process of obtaining values: “here’s how values will appear, and here’s how you can consume them.” Kotlin docs put it very directly: Flow produces values only when it is actively collected, while Channel lets coroutines send and receive values, and each value is delivered to exactly one receiver.

To feel the difference, a real-life analogy helps. Channel is like a mailbox (or a service queue): someone drops letters in, someone takes them out, letters accumulate (if there’s room), and it’s important to “close intake” so everyone understands there won’t be any new letters. Flow is more like a guided tour script: “first we’ll show room No. 1, then room No. 2...,” but the tour only actually starts when visitors arrive and say: “Alright, lead the way!”

2. What is Flow<T>: a stream description, not a data container

When we say val list = listOf(1, 2, 3), we are holding data in our hands (the container is already filled). When we say val channel = Channel<Int>(), we are holding a communication primitive: something can be sent into it, something can be received from it. But val f: Flow<Int> = ... is more like a contract: “here is where and how numbers will come from.”

And this is an important mental switch. Flow is not a “queue of values” where they are already sitting and waiting for you. It’s closer to a function: you describe how they will appear, and execution starts later.

Flow has two key words you need to get comfortable with today:

  • flow { ... } — a builder that creates a Flow.
  • collect { ... } — a collector (a terminal operation) that starts the stream execution and receives values.

And one more principle worth keeping in mind from the very beginning: without collect, “nothing happens.” This is not a metaphor or philosophy; it is literally how Flow behaves: until you collect it, the stream does not start.

3. A minimal Flow: flow { emit() } and collect { ... }

Now we’ll write the smallest example you can call “hello, Flow.” There will be no transformation operators (that’s for the next lecture), just a value source and a collector.

Pay attention to the structure: collect is suspend, so you must call it in a coroutine context (for example, inside runBlocking, which we already used in the coroutine lectures).


import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.collect

fun main() = runBlocking {
    val numbers = flow {
        emit(1)
        emit(2)
        emit(3)
    }

    numbers.collect { v ->
        println("v=$v")              // v=1, then v=2, then v=3
    }
}

It’s important to see two “layers” here.

Inside flow { ... }, we describe how values will appear: “emit 1, then 2, then 3.”

And inside collect { ... }, we describe what to do with each value when it appears: “print it.”

You don’t see any close()—because Flow completes differently: the stream ends when the code in flow { ... } ends. In other words, “end of stream” is simply “we reached the end of the block.”

4. Cold behavior of Flow in practice

From the previous examples, it might seem like Flow is just “another way to iterate 1, 2, 3.” But the real power begins when values appear not instantly, but over time. And here Flow naturally plays well with coroutines: you can do delay between emit calls.

delay inside flow: values appear over time

This is a good place to feel that Flow is a sequence of values spread out over time, yet it is collected sequentially (within a single collect).

import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.collect

fun main() = runBlocking {
    val ticks = flow {
        emit("tick")
        delay(200)
        emit("tock")
        delay(200)
        emit("done")
    }

    ticks.collect { word ->
        println(word)                // tick, then tock, then done
    }
}

You can think of this as a “small generator”: it emits a value, then waits, then emits another one. And all of this happens only because someone called collect.

Why Flow is called a cold stream

The word cold sounds like the stream got offended at you and refuses to heat the radiators. In practice, the meaning is simpler: no consumer means no production. If nobody is collecting values, flow { ... } will not even start executing.

Let’s demonstrate this as honestly as possible: we’ll add a println inside flow { ... } to see the start moment.

import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.collect

fun main() = runBlocking {
    val f = flow {
        println("Flow started")      // we'll see it only during collect
        emit(10)
    }

    println("Before collect")        // Before collect
    f.collect { println("v=$it") }   // Flow started; v=10
}

If you run it, you’ll see that the "Flow started" line appears after "Before collect", i.e., actually during collect, not at the moment f is created.

And that is the central idea. With Channel, you can start sending values “into nowhere” (and later someone will receive them) if there is a buffer, or if the sender will wait. But Flow is not a queue and not a “storage place.” By itself it does not “accumulate” anything: it executes.

Two collect calls mean two executions

Now let’s run a small experiment: we’ll collect the same Flow twice. If you’re used to collections, you might expect: “Well, we collected it, so the second time we’ll just walk through the same data again.” But a cold stream has different logic: each collect starts execution from scratch.

import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.collect

fun main() = runBlocking {
    val f = flow {
        println("Producing...")
        emit(1)
    }

    f.collect { println("first collect: $it") }
    // Producing...
    // first collect: 1

    f.collect { println("second collect: $it") }
    // Producing...
    // second collect: 1
}

Here “Producing...” is printed twice—that’s the practical meaning of a cold stream.

A helpful way to lock it in: Flow is closer to a “cooking recipe” (you can make it many times), while Channel is closer to a “pot of soup” (you poured it in—and whoever got there first eats it).

5. Flow and Channel: choosing the right model

This is an important part: we won’t just list differences; we’ll connect them to what problem you’re solving. And it helps to keep a “world model” in mind.

Channel models a message queue between coroutines: “someone sent, someone received.” Kotlin docs phrase it like this: a channel lets coroutines send and receive values, and each value is delivered to exactly one coroutine. This directly hints at distributing work among multiple consumers.

Flow models a stream of values over time: “a source emits values, and a consumer collects them.” And the key point: Flow emits values only when it is collected. So it naturally looks like “source → collect.”

To make it easier to compare without internal pain, let’s summarize the main differences in a table:

Topic Channel Flow
Main idea Communication: deliver a message between coroutines Value stream: describe how values appear over time
When it starts A sender can start send immediately (but it may suspend) The source starts only on collect (cold)
“End of data” Usually you need close() as a completion signal Completion = the end of the flow { ... } block
Multiple consumers One value is received by only one receiver Each collect restarts the stream (in the general case)
Feels like Queue/mail/task feed Generator/recipe/emission script

Here’s a typical practical selection criterion (without fanaticism). If you’re designing a system like “there are workers; we need to distribute tasks among them,” a channel often feels more natural. If you’re designing a system like “there is a data source; I want to sequentially get values and process them,” Flow is usually easier to read and describes the intent more “honestly.”

Why you can’t do send in Flow (and why that’s fine)

Sometimes a beginner tries to use Flow like a channel: “So how do I do send now?” The answer is simple: you don’t. And it’s not because Kotlin developers “forgot to add a method,” but because it’s a different tool for a different job.

Flow is a stream from a source to a consumer. There is no shared “box” where you can throw messages in from different places. This is a deliberate limitation: it forces you to keep the architecture cleaner. The source is described in one place, collection in another, and you don’t get “random” sends from all over the program that are impossible to track later.

If you need communication like “many coroutines send, many coroutines receive,” that’s channel territory. If you need the model “values arrive over time; I collect them,” then Flow will feel right at home.

6. A mini event monitor: Flow in a console app

So the examples don’t live their own life “in a vacuum,” let’s continue building the small application we already mentally used with channels: a console event monitor. Previously we could pass events through Channel<String>, and now we’ll make a version where the event source is a Flow<String>.

We’re not doing networking, files, or anything “external” (it’s unnecessary today). We simply simulate events: “app started,” “connection established,” “running,” “shutdown.”

A function that returns a Flow

Let’s start with a small function that creates a stream. It’s important to get used to this: unlike Channel, where you create an object and then “push” into it, with Flow you more often write a function describing “how to get values.”

import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow

fun buildStatusFlow(): Flow<String> = flow {
    emit("START")
    delay(150)
    emit("CONNECTED")
    delay(150)
    emit("RUNNING")
    delay(150)
    emit("STOP")
}

Here we neatly wrote a status “recipe.” It prints nothing and starts nothing—it just returns a Flow<String>.

collect in main: start and print

Now let’s use it in main. Yes, runBlocking again: we’re in a console app, and collect is suspend, so we need a coroutine context.

import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.flow.collect

fun main() = runBlocking {
    val statusFlow = buildStatusFlow()

    statusFlow.collect { status ->
        println("status=$status")
        // status=START, then CONNECTED, RUNNING, STOP
    }
}

Notice an important discipline: the stream describes the values, and main decides what to do with them. This makes the code more predictable: the source doesn’t print “secretly” (unless you explicitly want it to), and you don’t lose control.

Cold behavior demo: collect one stream twice

And to nail the cold nature into memory, you can add a small “replay mode”: collect the same stream twice.

import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.flow.collect

fun main() = runBlocking {
    val statusFlow = buildStatusFlow()

    println("First run:")
    statusFlow.collect { println(it) }     // START ... STOP

    println("Second run:")
    statusFlow.collect { println(it) }     // START ... STOP (again)
}

If you saw the statuses repeat—congrats, you just felt a cold stream rather than merely reading the definition.

7. Typical mistakes when first meeting Flow

Mistake #1: expecting Flow to start working by itself.
A very common trap is to write val f = flow { emit(1) } and expect “well, it’s created, so somewhere out there 1 has already been emitted.” No: a cold stream won’t execute until you explicitly call collect. If you see “nothing is printed,” first check whether you have a collector.

Mistake #2: confusing Flow with a message queue and looking for send.
If you start “translating” your code from Channel to Flow mechanically, you’ll quickly run into the question “where do I send it?” The answer: Flow is not about “sending,” it’s about “emitting.” Usually that means instead of “create a channel and hand it out to everyone,” you write a function that returns a Flow, and you describe value production inside flow { ... }.

Mistake #3: forgetting that collect is suspend and trying to call it from a regular function.
This looks like the typical compiler error: “Suspend function 'collect' should be called only from a coroutine or another suspend function”. The fix is exactly what you already know: either call collect inside runBlocking (in a console main), or make your function suspend and call it from a coroutine.

Mistake #4: being surprised that two collect calls do the work twice.
Beginners often treat Flow like “a list, just asynchronous.” So a repeated collect feels like “re-reading the same data.” In reality, it’s a restart. This is useful (you can reuse the stream like a recipe), but if you didn’t expect it, you might accidentally run expensive work twice. At the beginning of the course, it’s enough to remember the rule: a cold stream typically restarts on each collection.

Mistake #5: mixing responsibilities between source and consumer.
When you start printing to the console, mutating global variables, and doing “half an app” inside flow { ... }, the code quickly becomes muddy: it’s unclear who controls output and when things happen. In the early steps it’s better to keep a familiar discipline: the source does emit, the consumer does collect and decides what to print and how to react. This makes the behavior easier to understand, especially when later you start collecting longer pipelines.

1
Task
Kotlin SELF, level 54, lesson 2
Locked
Three signals
Three signals
1
Task
Kotlin SELF, level 54, lesson 2
Locked
Cold start
Cold start
1
Task
Kotlin SELF, level 54, lesson 2
Locked
Double collection
Double collection
1
Task
Kotlin SELF, level 54, lesson 2
Locked
System statuses
System statuses
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION