Flow operators help you change or pick data from a stream step by step. They make working with lists of data easy and clear.
0
0
Flow operators (map, filter, transform) in Kotlin
Introduction
When you want to change each item in a list to a new form.
When you want to keep only some items from a list based on a rule.
When you want to do complex changes or multiple steps on data flowing through.
When you want to process data one piece at a time without waiting for the whole list.
When you want to write clean and readable code for data streams.
Syntax
Kotlin
flowOf(1, 2, 3, 4, 5) .map { it * 2 } .filter { it > 5 } .transform { emit(it) emit(it + 1) }
map changes each item to something new.
filter keeps only items that match a condition.
transform lets you emit zero, one, or many items for each input.
Examples
This multiplies each number by 10.
Kotlin
flowOf(1, 2, 3) .map { it * 10 }
This keeps only even numbers.
Kotlin
flowOf(1, 2, 3, 4) .filter { it % 2 == 0 }
This emits the original number and then the number times 100.
Kotlin
flowOf(1, 2) .transform { emit(it) emit(it * 100) }
Sample Program
This program creates a flow of numbers 1 to 5. It multiplies each by 3, keeps only those greater than 7, then for each number it emits the number and the number plus one. Finally, it prints all emitted numbers.
Kotlin
import kotlinx.coroutines.flow.* import kotlinx.coroutines.runBlocking fun main() = runBlocking { flowOf(1, 2, 3, 4, 5) .map { it * 3 } // multiply each by 3 .filter { it > 7 } // keep numbers greater than 7 .transform { emit(it) // emit the number emit(it + 1) // emit number plus one } .collect { println(it) } // print each emitted number }
OutputSuccess
Important Notes
Use map when you want exactly one output per input.
Use filter to remove unwanted items.
transform is more flexible and can emit many or no items per input.
Summary
map changes each item in the flow.
filter keeps only items that match a condition.
transform lets you emit any number of items for each input.