Junior — Middle
Explain the differences between zip and combine operations in Kotlin Flow.
sobes.tech AI
Answer from AI
In Kotlin Flow, the zip and combine operations are used to merge multiple streams but work differently:
-
zipcombines elements from two (or more) streams in pairs, waiting for each stream to emit the next element. The result is formed from pairs of elements with the same index. If one stream completes, the combined stream also completes. -
combinereacts to any new value from any of the streams and combines the latest value of each. That is, when a new value appears in one of the streams,combineimmediately emits a result with the latest values of all streams.
Example:
val flow1 = flowOf(1, 2, 3)
val flow2 = flowOf("A", "B", "C", "D")
flow1.zip(flow2) { a, b -> "$a$b" } // will emit: "1A", "2B", "3C"
flow1.combine(flow2) { a, b -> "$a$b" } // will emit: "1A", "2A", "2B", "3B", "3C", "3D"
Thus, zip synchronizes elements by order, while combine does so by the latest available values.