# Combining Operators

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

## Combining Operators in Kotlin Flow

In this lesson, you’ll explore combining operators in Kotlin Flow. These operators let you merge and join multiple data flows. You’ll cover the following operators:

## The zip Operator

Suppose you have two flows: one for different carrot types and another for various carrot processing techniques. You can use zip to combine these flows into a single flow that pairs each carrot type with a processing method:

val carrotTypes = flowOf("Nantes", "Imperator", "Chantenay")
val processingMethods = flowOf("Wash", "Peel", "Chop")

fun processCarrots(): Flow<Pair<String, String>> =
carrotTypes.zip(processingMethods) { type, method -> type to method }
.collect { pair ->
println("Carrot type: \${pair.first}, Processing method: \${pair.second}")
}
Carrot type: Nantes, Processing method: Wash
Carrot type: Imperator, Processing method: Peel
Carrot type: Chantenay, Processing method: Chop

## The combine Operator

Now, suppose you have two flows: one for the current temperature in the carrot factory and another for the humidity level. You want to create a flow that emits the latest temperature and humidity when either changes:

val temperatureFlow = flowOf(25, 27, 29) // Degrees Celsius
val humidityFlow = flowOf(40, 45, 50)   // Percent humidity

fun monitorCarrotFactoryConditions(): Flow<Pair<Int, Int>> =
temperatureFlow.combine(humidityFlow) { temp, humidity -> temp to humidity }
.collect { pair ->
println("Temperature: \${pair.first}°C, Humidity: \${pair.second}%")
}
Temperature: 25°C, Humidity: 40%
Temperature: 27°C, Humidity: 45%
Temperature: 29°C, Humidity: 50%
val temperatureFlow = flowOf(25, 27, 29).onEach { delay(300) } // Degrees Celsius with delay
val humidityFlow = flowOf(40, 45, 50).onEach { delay(400) }   // Percent humidity with delay

fun monitorCarrotFactoryConditions(): Flow<Pair<Int, Int>> =
temperatureFlow.combine(humidityFlow) { temp, humidity -> temp to humidity }
.collect { pair ->
println("Temperature: \${pair.first}°C, Humidity: \${pair.second}%")
}
Temperature: 25°C, Humidity: 40%
Temperature: 27°C, Humidity: 40%
Temperature: 27°C, Humidity: 45%
Temperature: 29°C, Humidity: 45%
Temperature: 29°C, Humidity: 50%

## Wrap-Up

In this lesson, you’ve explored key combining operators in Kotlin Flow, including zip and combine. You’ve seen how these operators can be used to merge multiple flows, letting you create more complex data processing pipelines and respond to changes in real time.