map, filter and transform

Flow and StateFlow Junior Kotlin 2.0+ API 24+ Reviewed By Best Latest Apps

Predict the output

What does this print?

fun main() = runBlocking {
    flowOf(1, 2, 3, 4)
        .onEach { print("e$it ") }
        .filter { it % 2 == 0 }
        .map { it * 10 }
        .collect { print("c$it ") }
}
Options
Hint 1 of 1

Does a flow process one value at a time or the whole list first?

Choose an answer, then open Show answer below to check it.

Show answer

Answer: A e1 e2 c20 e3 e4 c40

Correct. Each value goes through the whole chain before the next one starts.

Why not the others?
  • B e1 e2 e3 e4 c20 c40. That would be true for a List; flows are processed one value at a time.
  • C c20 c40. onEach runs for every value, even ones filtered out later.
  • D Nothing, because onEach doesn't collect. collect at the end starts the flow.

30-second answer

They are intermediate operators: each returns a new cold flow and does nothing until a terminal operator such as collect, first or toList runs. map changes each value, filter drops some, onEach runs a side effect and passes the value through, and transform can emit any number of values per input.

Practise saying it · 30 s. No recording, just a timer

Explain intermediate vs terminal flow operators.

Say your answer out loud, then check which of these points you covered:

  • Intermediate operators return cold flows
  • Nothing runs until a terminal operator
  • Values pass one at a time
  • take and first cancel upstream

Deep dive

Operators run sequentially in the collector's coroutine by default, one value at a time through the whole chain.

take(n) cancels the upstream after n values, which is how you stop an infinite flow.

distinctUntilChanged skips consecutive duplicates; StateFlow already does this.

Terminal operators suspend: first() returns the first value and cancels the rest.

Common mistakes

  • Expecting onEach { } alone to start the flow.
  • Thinking each operator processes the whole stream before the next starts.
  • Using collect to get a single value instead of first().

Senior take & follow-ups

Show that values flow one at a time through the chain. The predict exercise is a classic warm-up.

Follow-up questions

Think of your answer first, then open the hint.

  1. What does launchIn(scope) do?

    Show hint

    Starts collecting in a new coroutine in that scope; it's collect in a launch.

  2. How do you get only the latest value now?

    Show hint

    first() on a StateFlow, or state.value.

Suggest a fix if something here is wrong or out of date.