combine and zip: Merging Multiple Flows
Combine multiple Flows and zip their emissions together.
Why Merge Flows?
Real apps often need to combine multiple data streams: user preferences + network data, form fields + validation state. Kotlin Flow provides zip, combine, and merge for this.
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
fun main() = runBlocking {
val names = flowOf("Alice", "Bob", "Carol")
val ages = flowOf(30, 25, 35)
names.zip(ages) { name, age -> "$name is $age" }
.collect { println(it) }
}zip: Paired Emissions
zip pairs emissions one-to-one in order. It stops when the shorter flow ends.
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
fun main() = runBlocking {
val a = flowOf(1, 2, 3, 4) // 4 elements
val b = flowOf("a", "b", "c") // 3 elements — zip stops here
a.zip(b) { n, s -> "$n-$s" }
.collect { println(it) } // 1-a, 2-b, 3-c
}All lessons in this course
- Flow Operators: map, filter, transform, and take
- catch and onCompletion: Error Handling in Flow
- combine and zip: Merging Multiple Flows
- flowOn and buffer: Context and Backpressure