combine vs zip

Flow and StateFlow Mid-level Kotlin 2.0+ API 24+ Reviewed By Best Latest Apps

Predict the output

What does this print?

fun main() = runBlocking {
    val letters = flowOf("a", "b", "c")
    val numbers = flowOf(1, 2)
    letters.zip(numbers) { l, n -> "$l$n" }
        .collect { print("$it ") }
}
Options
Hint 1 of 2

Does zip ever reuse a value?

Hint 2 of 2

What happens when one flow runs out?

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

Show answer

Answer: A a1 b2

Correct. zip pairs items one-to-one and stops when the shorter flow completes.

Why not the others?
  • B a1 b2 c2. That's combine-like behaviour with the latest value; zip never reuses a value.
  • C a1 b1 b2 c2. That's what combine can produce when sources emit at different times.
  • D a1 b2 c. zip needs a value from both flows for every item.

30-second answer

combine emits whenever either flow emits, using the latest value from each, once both have emitted at least once. zip pairs values one-to-one: the first with the first, the second with the second, and waits for both. Use combine for UI state built from several sources; zip is rarely right for UI.

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

Compare combine and zip.

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

  • combine uses the latest of each
  • Emits once all sources have a value
  • zip pairs one-to-one
  • Use combine for UI state

Deep dive

combine of three StateFlows is the usual way to build a screen's UiState.

zip completes when either flow completes, and a fast flow waits for the slow one.

merge interleaves values from several flows of the same type without combining them.

combine with more than five flows takes an array and loses types; group related state first.

Common mistakes

  • Using zip for UI state, so the screen freezes until both sources emit again.
  • Expecting combine to emit before every source has a value.
  • Using combine when you only want to interleave events (that's merge).

Senior take & follow-ups

A marble diagram in words wins this question; say what is emitted when, not just the definitions.

Follow-up questions

Think of your answer first, then open the hint.

  1. What does combine do when only one source emits?

    Show hint

    Nothing until every source has emitted once.

  2. When is zip useful?

    Show hint

    Pairing two sequences, such as requests with their responses.

Compare on iOS: merge vs zip Combine has the same three: combineLatest, zip and merge.

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