Kotlin Flow
Hot Flow vs Cold Flow
Section titled “Hot Flow vs Cold Flow”| Type | Description | Example |
|---|---|---|
| Cold Flow | Starts emitting only when collected, each collector gets its own stream | flow { }, flowOf() |
| Hot Flow | Emits regardless of collectors, shared among all collectors | StateFlow, SharedFlow |
Cold Flow
Section titled “Cold Flow”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 composableLaunchedEffect(Unit) { fetchData().collect { value -> println("Received: $value") }}Flow Operators
Section titled “Flow Operators”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 */ }Convert Flow to StateFlow
Section titled “Convert Flow to StateFlow”val stateFlow = flow.stateIn( scope = viewModelScope, started = SharingStarted.WhileSubscribed(5000), initialValue = emptyList())SharingStarted Options
Section titled “SharingStarted Options”| Option | Description |
|---|---|
Eagerly | Start immediately, never stop |
Lazily | Start on first collector, never stop |
WhileSubscribed(ms) | Start on first collector, stop after last collector + timeout |