Skip to content
Tutorials Center
My learning

Topics

Lesson 59 of 104 ยท App Architecture

StateFlow and collectAsStateWithLifecycle

Expose UI state from a ViewModel with StateFlow, share it with stateIn and WhileSubscribed, combine sources and collect safely in Compose with collectAsStateWithLifecycle.

A ViewModel holds state, and a composable needs to draw it and redraw it when it changes. The bridge between the two on modern Android is a Kotlin StateFlow: a flow that always has a current value, that replays that value to every new collector and that only emits when the value actually changes. On the Compose side, the function collectAsStateWithLifecycle() turns that flow into Compose state, and does it in a way that stops collecting when the app is not visible.

This lesson shows how to expose state as a StateFlow, how to build it from other flows with combine and stateIn, why the WhileSubscribed(5_000) option is the usual choice, how to collect safely and why new code does not use LiveData. It builds on StateFlow and SharedFlow in Kotlin, so read that first if MutableStateFlow is new to you. The Compose code is read-only (it needs the Android SDK); the TryIt blocks are stand-ins that use the real kotlinx.coroutines flows on the site's Kotlin runner, with a plain collector playing the part of the composable.

Exposing state from a ViewModel

The standard pattern has a private mutable flow and a public read-only view:

Kotlin
// read-only example: needs androidx.lifecycle
class CounterViewModel : ViewModel() {
    private val _uiState = MutableStateFlow(CounterUiState())
    val uiState: StateFlow<CounterUiState> = _uiState.asStateFlow()

    fun increment() {
        _uiState.update { it.copy(count = it.count + 1) }
    }
}

data class CounterUiState(val count: Int = 0)

Two details matter. asStateFlow() hands out a read-only view, so the UI cannot assign to value. And update { } changes the value atomically: it reads, computes and writes in a loop that retries on conflict, which is safer than _uiState.value = _uiState.value.copy(...) when several coroutines can write.

StateFlow has three properties worth remembering:

  • It always has a value (.value never blocks and is never absent), so the UI always has something to draw.
  • It is conflated: if the value changes several times before a collector gets to run, the collector sees only the latest.
  • It is equality-based: assigning a value that equals the current one emits nothing. That is why UI state classes should be immutable data classes. Mutating a list in place and assigning the same list object does not trigger an update; assign a new list (items + newItem, list.toList()).

The first stand-in shows conflation and equality with real flows. A collector in a coroutine plays the role of the UI.

Kotlin StateFlow: conflation and equality (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Notice that the collector never sees counts 1 and 2: it receives the initial state, then the latest state, then the labelled one. For UI state that is exactly right. You want to draw the current truth, not replay history. (For one-off happenings where every item counts, see the effects discussion in UI State, Events and MVI-style Modelling.)

Building state from other flows

Real screens combine several sources: the articles from the repository, the search query, a filter. combine takes the latest value of each flow and runs a function whenever any of them changes. stateIn then turns the resulting cold flow into a StateFlow that is shared by every collector:

Kotlin
// read-only example
class ArticlesViewModel(repository: ArticleRepository) : ViewModel() {
    private val query = MutableStateFlow("")

    val uiState: StateFlow<ArticlesUiState> =
        combine(repository.observeArticles(), query) { articles, q ->
            ArticlesUiState.Content(
                query = q,
                articles = articles.filter { it.title.contains(q, ignoreCase = true) },
            )
        }.stateIn(
            scope = viewModelScope,
            started = SharingStarted.WhileSubscribed(5_000),
            initialValue = ArticlesUiState.Loading,
        )

    fun onQueryChange(newQuery: String) {
        query.value = newQuery
    }
}

stateIn takes three arguments:

  • scope: where the sharing coroutine runs, normally viewModelScope.
  • started: when the upstream flow should be active.
  • initialValue: what the StateFlow holds until the first real value arrives (here, the loading state).

SharingStarted: when does the upstream run?

The three choices differ in cost and responsiveness:

Option Upstream runs Notes
Eagerly Immediately, until the scope is cancelled Does work even if no screen is visible
Lazily From the first collector until the scope is cancelled Never stops once started
WhileSubscribed(stopTimeoutMillis) While at least one collector exists, plus a timeout after the last one leaves Saves work while in the background

WhileSubscribed(5_000) is the convention on Android. When the app goes to the background, the UI stops collecting (see the next section) and, five seconds later, the upstream stops, so database observers, location updates or socket connections are not running for nothing. But rotation, which takes less than a second, does not restart the upstream: the new activity collects again within the timeout, and the flow carries on without reloading. The 5 seconds is a long-standing recommendation, not a magic number: it only has to be longer than a configuration change and short enough to be worth the savings.

By default the last value is kept after the upstream stops (replayExpirationMillis is infinite), so when the user returns they see the previous state immediately while the upstream restarts.

Collecting safely in Compose

A composable cannot call a suspend function directly, so it needs a bridge from flow to state. There are two:

Kotlin
// read-only example
@Composable
fun ArticlesRoute(viewModel: ArticlesViewModel = viewModel()) {
    val uiState by viewModel.uiState.collectAsStateWithLifecycle()
    ArticlesScreen(
        state = uiState,
        onQueryChange = viewModel::onQueryChange,
    )
}

collectAsStateWithLifecycle() comes from the androidx.lifecycle:lifecycle-runtime-compose library. It starts collecting when the lifecycle reaches STARTED and stops collecting when it drops below it, for instance when the user presses Home. You can change that with minActiveState. The plain collectAsState() collects for as long as the composable is in the composition. In an activity, the composition is kept while the activity is stopped, so collectAsState() keeps the upstream busy in the background and defeats WhileSubscribed.

For a StateFlow the function needs no initial value (the flow has one). For an ordinary Flow you must pass initialValue, because the flow may not have produced anything yet.

sequenceDiagram
    participant UI as Composable
    participant VM as ViewModel StateFlow
    participant Up as Upstream (database)
    UI->>VM: collect (screen STARTED)
    VM->>Up: start (first subscriber)
    Up-->>VM: values
    VM-->>UI: latest state
    UI->>VM: stop collecting (screen STOPPED)
    Note over VM,Up: after 5 s without subscribers
    VM->>Up: cancel upstream

Lifecycle-aware collection plus WhileSubscribed stops all work while nobody is watching.

In classic View-based code you would get the same behaviour with repeatOnLifecycle(Lifecycle.State.STARTED) { flow.collect { ... } }, covered in Collecting Flows Safely.

Seeing WhileSubscribed work

The second stand-in has a ViewModel that builds its state with combine and stateIn(..., WhileSubscribed(500)). A simulated "screen" collects and stops: first normally, then across a quick rotation (collector cancelled and started again immediately), then for a real departure that lasts longer than the timeout. The upstream prints a line whenever it starts and stops.

Kotlin combine, stateIn and WhileSubscribed (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

In the output, the upstream starts when the first screen collects, is not restarted by the rotation, stops about half a second after the user leaves and starts again on return, while the ViewModel and its last value stay alive the whole time. That is the behaviour WhileSubscribed(5_000) gives a real app.

Why not LiveData?

LiveData was the original lifecycle-aware observable and you will meet it in older code. For new code, StateFlow is preferred:

  • It is plain Kotlin from kotlinx.coroutines, so it works in repositories and in non-Android modules, with no Android dependency.
  • It has the full flow operator set (combine, map, debounce, flatMapLatest), while LiveData has little beyond map and switchMap.
  • It always has a non-null value and integrates with coroutines for testing.
  • Compose collects flows directly with collectAsStateWithLifecycle().

LiveData is not removed and still works: observeAsState() exists for Compose, and flow.asLiveData() and liveData.asFlow() convert between them during a migration. You do not need to rewrite working code; just do not start new screens with it.

Common mistakes

  • Exposing MutableStateFlow publicly. Expose StateFlow through asStateFlow().
  • Mutating a list in place and expecting an update. Replace the value with a new list.
  • Using collectAsState() for screens with expensive upstreams. Use collectAsStateWithLifecycle().
  • Collecting in LaunchedEffect with launch and no lifecycle handling, which keeps collecting in the background.
  • SharingStarted.Eagerly for everything, so database and location work runs with nobody watching.
  • Using SharedFlow for state. It has no current value and no equality check; use StateFlow.
  • Reading .value in a composable instead of collecting. The composable would not be redrawn when it changes.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A StateFlow value is set to 1, 2 and 3 in quick succession before the collector runs. What does the collector see?

    StateFlow conflates: it keeps only the latest value for collectors that are slower than the writers, which suits UI state.
  2. 2. Why is WhileSubscribed(5_000) a good default for stateIn in a ViewModel?

    A rotation re-subscribes well within the timeout, so no reload happens, while a real trip to the background stops the upstream work.
  3. 3. What does collectAsStateWithLifecycle do that collectAsState does not?

    By default it collects only while the lifecycle is at least STARTED, so upstream work pauses in the background. collectAsState keeps collecting while the composition exists.
  4. 4. You append to a MutableList inside a StateFlow<MutableList<String>> and assign the same list object back. What happens?

    StateFlow compares values with equals. The same object is equal to itself, so there is no emission. Use immutable lists and assign a new copy.

Summary

  • Expose UI state as a read-only StateFlow, built from a private MutableStateFlow and asStateFlow(); change it with update { }.
  • StateFlow always has a value, conflates fast updates and ignores equal values, so use immutable data classes and new lists.
  • Build state from other flows with combine, then share it with stateIn(viewModelScope, WhileSubscribed(5_000), initialValue).
  • WhileSubscribed(5_000) survives rotation without reloading and stops upstream work in the background.
  • Collect in Compose with collectAsStateWithLifecycle(), which pauses below STARTED; avoid plain collectAsState() for heavy upstreams.
  • Prefer StateFlow to LiveData in new code; interop helpers exist for migration.
  • The Compose code is read-only; the TryIts run the real flow operators with a plain collector as the stand-in UI.

Next: The Repository Pattern and Data Sources