Flow — Basics
Flow in Kotlin is an asynchronous data stream. Use flow { emit() } to emit values sequentially, and collect { } to receive them. Unlike lists, flows are evaluated lazily, making them well suited for processing large amounts of data or continuous event streams.
Syntax
// Create a Flow
val flow: Flow<Type> = flow {
emit(value) // Emit a value
emit(value2)
}
// Collect a Flow (must be called inside a coroutine)
flow.collect { value ->
// Process each received value
}
// Transformation (intermediate operators)
flow.map { it * 2 }
.filter { it > 3 }
.collect { println(it) }
Function List
| Function / Operator | Description |
|---|---|
| flow { emit() } | Creates a new Flow. Call emit() inside the block to emit values. |
| flowOf(vararg) | Creates a Flow that emits the specified values. |
| List.asFlow() | Converts a list into a Flow. |
| flow.collect { } | Receives and processes each value from the Flow (terminal operator). |
| flow.map { } | Transforms each emitted value (intermediate operator). |
| flow.filter { } | Passes only values that match the condition (intermediate operator). |
| flow.take(n) | Takes only the first n values (intermediate operator). |
| flow.toList() | Collects all values into a list (terminal operator). |
Sample Code
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
// A function that returns a Flow
fun countDown(): Flow<Int> = flow {
for (i in 5 downTo 1) {
delay(100) // Simulate async work
emit(i)
}
}
fun main() = runBlocking {
// Collect the Flow using collect.
countDown().collect { value ->
println("Count: $value")
}
// Create a Flow easily with flowOf.
flowOf("Apple", "Banana", "Cherry")
.map { it.uppercase() }
.filter { it.startsWith("B") || it.startsWith("A") }
.collect { println(it) }
// Convert a list to a Flow.
val total = (1..10).asFlow()
.filter { it % 2 == 0 } // Even numbers only
.map { it * it } // Square each value
.toList()
println(total) // [4, 16, 36, 64, 100]
// Limit the number of items with take.
(1..100).asFlow()
.take(3)
.collect { println(it) } // 1, 2, 3
}
Overview
Flow is Kotlin's asynchronous data stream, equivalent to RxJava's Observable, but seamlessly integrated with coroutines. It is a "cold stream" — execution does not begin until collect is called.
Intermediate operators such as map and filter are also lazily evaluated even when chained. Actual execution happens all at once when a terminal operator such as collect or toList is called.
For coroutine basics, see suspend functions. For data communication between coroutines, see Channel.
If you find any errors or copyright issues, please contact us.