Summary - Flow basics
- Kotlin course
- Intermediate
- Lesson 93/116
- 5 min
Combine flow, collect and map to write an event stream.
Summary - Flow basics
In this group you learned the cold stream nature of Flow, the flow { } builder and emit, the collect terminal operator, the map/filter intermediate operators and changing context with flowOn.
Now you will combine them: build a flow and transform it with map, then chain filter and flowOf. This structure is the foundation of asynchronous data streams in Kotlin. Later, StateFlow, SharedFlow and channel-based hot streams will build on it.
Practice flow builder and map chain
Define fun doubled(): Flow<Int> = flow { ... }.map { ... }. In the body use a for (i in 1..5) loop with emit(i); then apply .map { it * 2 }. Mark main with runBlocking; inside it call doubled().collect { println(it) }.
Starter code
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.runBlocking
// doubled function: inside flow { } emit 1..5, double each value
// main: collect the doubled flow and print
fun main() = runBlocking {
// write here
}Sample solution
fun doubled(): Flow<Int> = flow {
for (i in 1..5) {
emit(i)
}
}.map { it * 2 }
fun main() = runBlocking {
doubled().collect { println(it) }
}Expected output
2 4 6 8 10
Practice Squares with filter and map
Define fun squares(): Flow<Int> = flowOf(...).filter { ... }.map { ... }. Build the flow with flowOf(1, 2, 3, 4, 5); filter even with .filter { it % 2 == 0 }; square with .map { it * it }. Mark main with runBlocking; inside it call squares().collect { println(it) }.
Starter code
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.runBlocking
// squares function: build flowOf, filter even, square
// main: collect the squares flow and print
fun main() = runBlocking {
// write here
}Sample solution
fun squares(): Flow<Int> = flowOf(1, 2, 3, 4, 5)
.filter { it % 2 == 0 }
.map { it * it }
fun main() = runBlocking {
squares().collect { println(it) }
}Expected output
4 16
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which of the following is a terminal operator?
- map
- filter
- flowOn
- collect Correct answer
Explanation: collect is terminal; it runs the flow and consumes values.
2 Match the Flow concepts
| Term | Meaning |
|---|---|
flow { } |
Flow builder |
emit |
Sends a value |
collect |
Consumer |
flowOn |
Sets context |