Combining flows (zip, combine) in Kotlin - Time & Space Complexity
When we combine two flows in Kotlin, we want to know how the work grows as the flows get bigger.
We ask: how many steps does the program take when merging these flows?
Analyze the time complexity of the following code snippet.
val flow1 = flowOf(1, 2, 3)
val flow2 = flowOf("a", "b", "c")
val zippedFlow = flow1.zip(flow2) { num, str -> "$num$str" }
zippedFlow.collect { println(it) }
This code combines two flows by pairing their elements one by one and then prints each pair.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Pairing each element from the first flow with one from the second flow.
- How many times: Once for each element in the smaller flow until one flow ends.
As the flows get longer, the number of pairs grows with the size of the smaller flow.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 pairs created |
| 100 | 100 pairs created |
| 1000 | 1000 pairs created |
Pattern observation: The work grows directly with the number of elements to combine.
Time Complexity: O(n)
This means the time to combine grows in a straight line with the number of elements.
[X] Wrong: "Combining two flows takes time proportional to the product of their sizes."
[OK] Correct: The combination stops when the smaller flow ends, so it only grows with the smaller size, not both multiplied.
Understanding how combining streams or flows scales helps you write efficient reactive programs and explain your reasoning clearly.
"What if we used combine instead of zip, which emits on any new element from either flow? How would the time complexity change?"