0
0
Kotlinprogramming~5 mins

Combining flows (zip, combine) in Kotlin - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does the zip operator do when combining two Kotlin flows?
The zip operator pairs elements from two flows one by one, emitting a combined value only when both flows have emitted an element. It stops when the shortest flow ends.
Click to reveal answer
beginner
How does the combine operator differ from zip in Kotlin flows?
combine emits a new value every time any of the flows emits, using the latest values from both flows. It does not wait for both to emit simultaneously like zip.
Click to reveal answer
beginner
Show a simple Kotlin code snippet using zip to combine two flows of numbers.
val flow1 = flowOf(1, 2, 3) val flow2 = flowOf(10, 20, 30) flow1.zip(flow2) { a, b -> a + b } .collect { println(it) } // Outputs: 11, 22, 33
Click to reveal answer
intermediate
Explain what happens when one flow emits faster than the other in combine.
In combine, whenever any flow emits a new value, it combines that with the latest value from the other flow, even if the other flow hasn't emitted recently. This means faster emissions trigger more combined outputs.
Click to reveal answer
intermediate
What is a practical use case for using combine over zip in Kotlin flows?
Use combine when you want to react to changes from multiple sources independently, like updating UI with latest user input and network status, without waiting for both to emit simultaneously.
Click to reveal answer
What happens if one flow emits more items than the other when using zip?
AAn error is thrown.
BAll items from both flows are emitted regardless.
CThe flow with fewer items repeats its last value.
DThe extra items are ignored after the shortest flow ends.
Which operator emits a new combined value every time any flow emits?
Acombine
BflatMapConcat
Cmerge
Dzip
In Kotlin flows, what does zip require to emit a combined value?
AOnly one flow needs to emit.
BBoth flows must have emitted at least one value each.
CBoth flows must emit a new value at the same time.
DFlows must be merged first.
Which operator would you use to combine a flow of user input with a flow of network status to update UI reactively?
Acombine
Bzip
Cfilter
Dmap
What is the output of this code?<br>
val f1 = flowOf(1, 2)
val f2 = flowOf(10, 20, 30)
f1.zip(f2) { a, b -> a * b }.toList()
A[1, 2]
B[10, 20, 30]
C[10, 40]
D[10, 20]
Describe the difference between zip and combine when working with Kotlin flows.
Think about when each operator emits combined values.
You got /4 concepts.
    Give an example scenario where combine is more useful than zip.
    Consider flows that emit at different speeds.
    You got /3 concepts.