Combining flows lets you work with multiple streams of data together. It helps you get values from two flows at the same time and use them in one place.
0
0
Combining flows (zip, combine) in Kotlin
Introduction
When you want to pair items from two lists that come over time, like matching names and ages.
When you need to update UI based on two different data sources, like user input and network data.
When you want to react only when both flows have new values, like waiting for two sensors to send data.
When you want to merge two flows and create a new value from both, like combining temperature and humidity readings.
Syntax
Kotlin
val combinedFlow = flow1.zip(flow2) { value1, value2 -> // combine values here } val combinedFlow = flow1.combine(flow2) { value1, value2 -> // combine values here }
zip pairs values from both flows one by one, stopping when one flow ends.
combine emits new values whenever either flow emits, using the latest from both.
Examples
This pairs 1 with A, 2 with B, and 3 with C, producing "1A", "2B", "3C".
Kotlin
val flow1 = flowOf(1, 2, 3) val flow2 = flowOf("A", "B", "C") val zipped = flow1.zip(flow2) { a, b -> "$a$b" }
This emits a new combined value whenever either flow emits, using the latest values from both.
Kotlin
val flow1 = flowOf(1, 2, 3) val flow2 = flowOf("A", "B", "C") val combined = flow1.combine(flow2) { a, b -> "$a$b" }
Sample Program
This program shows how zip pairs items one by one and combine merges latest values from both flows.
Kotlin
import kotlinx.coroutines.* import kotlinx.coroutines.flow.* fun main() = runBlocking { val numbers = flowOf(1, 2, 3) val letters = flowOf("A", "B", "C") println("Using zip:") numbers.zip(letters) { n, l -> "$n$l" } .collect { println(it) } println("Using combine:") numbers.combine(letters) { n, l -> "$n$l" } .collect { println(it) } }
OutputSuccess
Important Notes
zip waits for both flows to emit before pairing values.
combine emits more often because it reacts to any new value from either flow.
Use zip when you want strict pairs, and combine when you want to react to any change.
Summary
zip pairs values one by one from two flows.
combine merges latest values from two flows whenever either emits.
Both help you work with multiple data streams together in Kotlin.