CodeBlanks Logo Icon CodeBlanks

flow builder

Learn to create Flows with flow { }.

The flow { } builder

The flow { ... } builder lets you build a flow imperatively. You write normal Kotlin code in the body; emit(value) sends each value to the consumer.

fun counter(): Flow<Int> = flow {
    for (i in 1..3) {
        emit(i)
    }
}

Here the loop calls emit(i) on each turn, passing the value to collect. emit is a suspend function; it waits until the consumer is ready. This makes the flow sequential: the next emit runs only after the consumer finishes.

emit and sequential execution

A flow body runs sequentially with its consumer. On each emit call the flow pauses; the collect lambda runs, and when it finishes the flow continues. So emit and collect handshake.

flow {
    emit("a")
    println("body")
}.collect { println(it) }

Output order: a, body. First emit("a") goes to collect, the lambda prints, then emit returns and the body continues. This is a consequence of the cold, sequential nature of flows.

Practice Build a number flow with the flow builder

Define fun counter(): Flow<Int> = flow { ... }. In the body use a for (i in 1..3) loop to emit(i) each value. Mark main with runBlocking; inside it call counter().collect { println(it) }.

Starter code

Main.kt
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.runBlocking

// counter function: inside flow { } emit 1, 2, 3
// main: inside runBlocking, collect the counter flow and print
fun main() = runBlocking {
    // write here
}

Sample solution

Main.kt
fun counter(): Flow<Int> = flow {
    for (i in 1..3) {
        emit(i)
    }
}

fun main() = runBlocking {
    counter().collect { println(it) }
}

Expected output

1
2
3

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Send a value

Question
fun counter(): Flow<Int> = flow {
    for (i in 1..3) {
        ____(i)
    }
}
Answer
fun counter(): Flow<Int> = flow {
    for (i in 1..3) {
        emit(i)
    }
}

Explanation: emit sends a value inside a flow body.

2 Match the flow builder parts

Term Meaning
flow { } Flow builder
emit(value) Sends a value
for (i in 1..3) Loop
Flow<Int> Return type

3 Which function sends a value to the consumer inside a flow { } body?

  • return
  • yield
  • send
  • emit Correct answer

Explanation: emit is the suspend function that sends a value inside a flow body.

All lessons in Intermediate