Kotlin Flow: flow, collect, StateFlow and SharedFlow

Kotlin course · Coroutines · Lesson 49 of 51

Updated:

A suspend function returns one value. A Flow returns many values over time: search results as the user types, a download’s progress, live prices or the rows of a database table that keeps changing.

Creating and collecting a flow

import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*

fun countdown(from: Int): Flow<Int> = flow {
    for (i in from downTo 1) {
        emit(i)            // send a value
        delay(100)
    }
}

fun main() = runBlocking {
    countdown(3).collect { value ->
        println(value)
    }
    println("Liftoff!")
}

Output:

3
2
1
Liftoff!
  • flow { } builds a flow, and emit() sends each value.
  • collect { } receives the values. It’s a suspend function, so it’s called inside a coroutine.

Flows are cold

A flow built with flow { } does nothing until someone collects it, and it starts again from the beginning for each collector:

import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*

val numbers = flow {
    println("Flow started")
    emit(1)
    emit(2)
}

fun main() = runBlocking {
    println("Before collecting")
    numbers.collect { println("A got $it") }
    numbers.collect { println("B got $it") }
}

Output:

Before collecting
Flow started
A got 1
A got 2
Flow started
B got 1
B got 2

Other ways to create flows

import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*

fun main() = runBlocking {
    flowOf("a", "b", "c").collect { print("$it ") }
    println()
    listOf(10, 20, 30).asFlow().collect { print("$it ") }
    println()
    (1..3).asFlow().collect { print("$it ") }
    println()
}

Output:

a b c 
10 20 30 
1 2 3 

Operators: transform the stream

Flow operators look like collection functions, but they work on values as they arrive:

import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*

fun main() = runBlocking {
    (1..10).asFlow()
        .filter { it % 2 == 0 }
        .map { it * it }
        .onEach { println("Got $it") }
        .take(3)
        .collect()

    val total = (1..5).asFlow().reduce { acc, n -> acc + n }
    println("Sum: $total")

    println((1..4).asFlow().map { "Item $it" }.toList())
}

Output:

Got 4
Got 16
Got 36
Sum: 15
[Item 1, Item 2, Item 3, Item 4]

Intermediate operators (map, filter, onEach, take) return a new flow and don’t run anything. Terminal operators (collect, toList, first, reduce) start the flow.

Handling errors and completion

import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*

fun prices(): Flow<Int> = flow {
    emit(100)
    emit(105)
    throw IllegalStateException("Connection lost")
}

fun main() = runBlocking {
    prices()
        .catch { e -> println("Error: ${e.message}"); emit(-1) }
        .onCompletion { println("Stream finished") }
        .collect { println("Price: $it") }
}

Output:

Price: 100
Price: 105
Error: Connection lost
Price: -1
Stream finished

catch handles errors from the steps above it, and can emit a fallback value.

Switching threads: flowOn

fun readLines(): Flow<String> = flow {
    // read a big file line by line
}.flowOn(Dispatchers.IO)     // the code above runs on IO; collect stays on the caller's thread

Don’t use withContext inside flow { } to change the thread of emit. Use flowOn instead.

StateFlow: a value that changes over time

A StateFlow always holds a current value, and sends every new value to its collectors. It’s the standard way to hold screen state in a ViewModel:

import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*

class CounterViewModel {
    private val _count = MutableStateFlow(0)
    val count: StateFlow<Int> = _count.asStateFlow()   // read-only for the UI

    fun increment() { _count.value++ }
}

fun main() = runBlocking {
    val vm = CounterViewModel()
    val job = launch { vm.count.collect { println("UI shows: $it") } }

    delay(50); vm.increment()
    delay(50); vm.increment()
    delay(50)
    println("Current value: ${vm.count.value}")
    job.cancel()
}

Output:

UI shows: 0
UI shows: 1
UI shows: 2
Current value: 2

A StateFlow is hot: it exists and holds its value whether or not anyone is collecting. It also skips a new value that’s equal to the current one.

SharedFlow: one-off events

A SharedFlow broadcasts values to all current collectors, but doesn’t hold a “current value” by default. It suits one-time events such as “show a snackbar” or “navigate to the next screen”:

import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*

fun main() = runBlocking {
    val events = MutableSharedFlow<String>()

    val job = launch { events.collect { println("Event: $it") } }
    delay(50)
    events.emit("Saved successfully")
    events.emit("Navigate to Home")
    delay(50)
    job.cancel()
}

Output:

Event: Saved successfully
Event: Navigate to Home

Flow vs StateFlow vs SharedFlow

FlowStateFlowSharedFlow
Cold or hotcoldhothot
Has a current valuenoyes (.value)no (optional replay)
Each collector getsits own run from the startthe latest value, then updatesvalues emitted while it collects
Typical usedata streams, database queriesUI stateone-off events

Using flows in Android

// ViewModel
val uiState: StateFlow<UiState> = repository.articles()       // Flow from Room or the network
    .map { UiState(articles = it) }
    .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), UiState())

// Jetpack Compose
val state by viewModel.uiState.collectAsStateWithLifecycle()

collectAsStateWithLifecycle() (from lifecycle-runtime-compose) collects only while the screen is visible, which saves battery and avoids crashes.

Common mistakes

  • Building a flow and never collecting it: nothing happens. A cold flow only runs when collected.
  • Exposing MutableStateFlow from a ViewModel: expose a read-only StateFlow with asStateFlow().
  • Using StateFlow for one-off events: it replays the latest value to new collectors, so an event like “show error” can fire again after rotation. Use a SharedFlow or state that the UI clears.

Exercise

Simulate a search box: the user types characters one by one; ignore queries shorter than 2 characters, and show results for each remaining query.

import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*

val fruits = listOf("apple", "apricot", "banana", "mango", "grape")

fun typing(): Flow<String> = flow {
    for (q in listOf("a", "ap", "apr", "m", "ma")) {
        emit(q)
        delay(100)
    }
}

fun main() = runBlocking {
    typing()
        .filter { it.length >= 2 }
        .map { q -> q to fruits.filter { it.startsWith(q) } }
        .collect { (q, results) -> println("\"$q\" -> $results") }
}

Output:

"ap" -> [apple, apricot]
"apr" -> [apricot]
"ma" -> [mango]

In a real app you’d add debounce(300) to wait until the user pauses typing, and distinctUntilChanged() to skip repeated queries.

FAQ

What is Flow in Kotlin?

A stream of values that are produced and received asynchronously, one after another, using coroutines.

What is the difference between Flow and StateFlow?

A Flow is cold: it runs from the start for each collector. A StateFlow is hot: it always holds a current value, and collectors get the latest value and then every update.

What is the difference between StateFlow and LiveData?

Both hold observable state. StateFlow is part of Kotlin coroutines, needs an initial value, works outside Android and has all the Flow operators. LiveData is Android-only and lifecycle-aware by default.

WhatsApp us📞 Call now