Flow (Kotlin)
Flow is Kotlin's coroutine-based type for an asynchronous stream of values emitted over time. It is cold and reactive: the producer runs only when a terminal collector subscribes.
Kotlin
Where a suspend function returns a single async value, a Flow<T> emits a sequence of values asynchronously. You build one with the flow { emit(x) } builder and consume it with the suspend function collect { }. Operators like map, filter, and take transform the stream much like collection operations.
Flows are cold: nothing runs until a terminal operator (collect) subscribes, and each collector triggers a fresh run. This makes them composable and back-pressure-friendly. For hot, multicast streams (shared state or events), use StateFlow and SharedFlow.
Because Flow is built on coroutines, emission and collection respect structured concurrency and cancellation. Flow is the idiomatic way to model things like database queries, websocket messages, or UI state changing over time.
Syntax
flow { emit(1); emit(2) }.collect { println(it) }Examples
Kotlin
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
fun main() = runBlocking {
flowOf(1, 2, 3)
.map { it * 10 }
.collect { println(it) }
}Output:
10
20
30