Skip to content

Kotlin Flow

TypeDescriptionExample
Cold FlowStarts emitting only when collected, each collector gets its own streamflow { }, flowOf()
Hot FlowEmits regardless of collectors, shared among all collectorsStateFlow, SharedFlow

Created using flow { } builder. Each collector triggers a new execution.

fun fetchData(): Flow<Int> = flow {
for (i in 1..5) {
delay(1000)
emit(i)
}
}
// Collect in composable
LaunchedEffect(Unit) {
fetchData().collect { value ->
println("Received: $value")
}
}
flow
.map { it * 2 } // Transform values
.filter { it > 10 } // Filter values
.debounce(300) // Wait for pause in emissions
.distinctUntilChanged() // Skip consecutive duplicates
.catch { e -> emit(default) } // Handle errors
.onEach { log(it) } // Side effects
.collect { /* use value */ }
val stateFlow = flow.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5000),
initialValue = emptyList()
)
OptionDescription
EagerlyStart immediately, never stop
LazilyStart on first collector, never stop
WhileSubscribed(ms)Start on first collector, stop after last collector + timeout