Flow
- Kotlin course
- Intermediate
- Lesson 88/116
- 5 min
Learn the cold stream concept with Flow.
Flow: Cold stream
A Flow is a cold asynchronous stream in Kotlin that produces values over time. Cold means the flow does not produce anything until a consumer calls collect. This differs from hot channels, which produce whether or not anyone listens.
Flow lives in the kotlinx.coroutines.flow package. The simplest builder is flowOf(1, 2, 3), which creates a flow of fixed values. To consume a flow you call collect { ... }; the lambda runs for each value. collect is a suspend function, so it runs inside a coroutine context such as runBlocking.
The flowOf builder
flowOf is the simplest Flow builder: it creates a flow from given fixed values. To turn an Iterable or Sequence into a flow, use .asFlow().
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.runBlocking
fun numbers(): Flow<Int> = flowOf(1, 2, 3)
fun main() = runBlocking {
numbers().collect { println(it)
}
}Output: 1, 2, 3 on separate lines. Because the flow is cold, calling numbers() alone produces nothing; collect triggers the values to be emitted in order.
Practice Define a simple Flow and consume it
Define fun numbers(): Flow<Int> = flowOf(1, 2, 3). Mark main with runBlocking; inside it call numbers().collect { println(it) }. The output prints each value on its own line.
Starter code
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.runBlocking
// numbers function: return a Flow<Int> of 1, 2, 3
// main: inside runBlocking, collect the numbers flow and print
fun main() = runBlocking {
// write here
}Sample solution
fun numbers(): Flow<Int> = flowOf(1, 2, 3)
fun main() = runBlocking {
numbers().collect { println(it) }
}Expected output
1 2 3
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What kind of stream is a Flow?
- A synchronous list
- A hot broadcast channel
- A cold asynchronous stream of values Correct answer
- A function returning a single value
Explanation: A Flow is a cold asynchronous stream; it produces when collect is called.
2 Complete the return type
fun numbers(): ____ = flowOf(1, 2, 3)
fun numbers(): Flow<Int> = flowOf(1, 2, 3)
Explanation: Flow<Int> specifies the value type of the flow.
3 Match the Flow parts
| Term | Meaning |
|---|---|
flow |
Stream |
cold |
Cold (collect triggers) |
collect |
Consumer |
flowOf |
Fixed-value builder |