What is Flow in Kotlin?
Tier: EssentialDifficulty: Easy
Flow is Kotlin's type for an asynchronous stream of values, built on coroutines, that emits zero or more items over time and then completes, with or without an error.
A Flow has three pieces.
- A builder, usually
flow { }, that produces values withemit(). - Intermediate operators like
maporfilterthat transform the stream without running it. - A terminal operator like
collectthat actually starts the flow and receives the values.
fun getNumbers(): Flow<Int> = flow {
for (i in 1..3) {
delay(100)
emit(i)
}
}
// nothing runs until this
getNumbers().collect { println(it) }
That last point is the one people miss. A Flow does nothing on its own, it's a cold, lazy sequence. Calling getNumbers() doesn't touch the network or run the loop, it just builds a description of the work. The block only executes when a collector calls collect, and it runs fresh for every new collector.
Flow exists because coroutines alone only get you a single suspended result. A suspend function returns one value once. Flow is the coroutine equivalent of a stream, useful for things like search results as the user types, rows from a Room query, or progress updates from a download, where you need many values over time instead of one.
Read more Asynchronous Flow (opens in a new tab)