How to Use Flow Map in Kotlin: Simple Guide
In Kotlin, you use
map on a Flow to transform each emitted value into a new value. The map operator takes a lambda that defines how to change each item as it flows through the stream.Syntax
The map operator is called on a Flow and takes a lambda function that transforms each emitted value. The syntax looks like this:
flow.map { value -> transformedValue }: Transforms eachvalueemitted by the flow.- The lambda returns the new value that replaces the original one in the flow.
kotlin
flow.map { value -> transformedValue }Example
This example shows how to create a flow of numbers and use map to multiply each number by 2 before collecting and printing the results.
kotlin
import kotlinx.coroutines.flow.* import kotlinx.coroutines.runBlocking fun main() = runBlocking { val numbersFlow = flowOf(1, 2, 3, 4, 5) val doubledFlow = numbersFlow.map { it * 2 } doubledFlow.collect { value -> println(value) } }
Output
2
4
6
8
10
Common Pitfalls
One common mistake is forgetting that map only transforms values but does not trigger the flow to start. You must collect the flow to see the results.
Another pitfall is using blocking code inside the map lambda, which can freeze the flow. Always use suspend functions or non-blocking code.
kotlin
import kotlinx.coroutines.flow.* import kotlinx.coroutines.runBlocking fun main() = runBlocking { val flow = flowOf(1, 2, 3) // Wrong: map without collect - no output flow.map { it * 10 } // Right: collect to trigger flow flow.map { it * 10 }.collect { println(it) } }
Output
10
20
30
Quick Reference
Remember these tips when using map with flows:
- map transforms each emitted value.
- You must collect the flow to execute it.
- Use non-blocking code inside
map. mapreturns a new flow with transformed values.
Key Takeaways
Use
map on a flow to transform each emitted value.Always collect the flow to start processing and see results.
Avoid blocking operations inside the
map lambda.map returns a new flow with the transformed data.Use
map for simple, synchronous transformations in flows.