Phase 4 · Data & PersistenceModule 38~28 min read

Kotlin Flow in the UI

Stream data reactively into Compose with Flow and StateFlow, collected safely.

What you'll learn

Some data doesn't arrive once — it streams. A database table changes, a location updates, a search query evolves keystroke by keystroke. Kotlin Flow models a stream of values over time, and it's how Room and DataStore hand you data. You've seen StateFlow already; now let's use flows properly.

By the end you'll be able to:

  • Distinguish a cold Flow from StateFlow/SharedFlow
  • Transform a flow with operators like map and filter
  • Combine several streams into one
  • Turn a flow into UI state and collect it safely

Cold flows vs StateFlow / SharedFlow

The three kinds you'll meet, and when each fits:

TypeNatureTypical use
Flow<T>Interface for streams; flow { } creates a cold producerObserve data or transform another stream
StateFlow<T>Hot — always has a current value, emits on changeUI state exposed by a ViewModel
SharedFlow<T>Hot broadcast with configurable replay and bufferingShared transient signals with an explicit delivery policy

A cold flow is lazy: nothing happens until someone collects it, and it starts fresh for each collector — like a recipe that only cooks when ordered. A hot flow (StateFlow/SharedFlow) is shared among collectors. Hot describes the stream's sharing behavior; it does not promise that an upstream producer is always actively working.

Note

Expose renderable state as StateFlow. A default SharedFlow with replay zero broadcasts only to active collectors; a signal emitted while nobody is collecting can be lost. Important outcomes should be represented as UI state with a deliberate acknowledgment policy.

Transforming flows

Flows compose like collections. Chain operators to build a pipeline — map to reshape each value, filter to drop some, distinctUntilChanged to skip duplicates. The transformation runs each time the source emits, keeping downstream always up to date.

Combining streams

combine merges several flows: whenever any source emits, it recomputes a result from the latest value of each. This is perfect for search — combine the live list of contacts with the current query to produce a filtered list — and stateIn converts that cold pipeline into a StateFlow the UI can read:

SearchViewModel.kt
class SearchViewModel(private val repo: ContactRepository) : ViewModel() {

    private val query = MutableStateFlow("")
    fun onQueryChange(q: String) { query.value = q }

    // A pipeline: raw contacts flow → filtered by the current query → UI state.
    val uiState: StateFlow<List<Contact>> =
        combine(repo.contacts, query) { contacts, q ->
            contacts.filter { it.name.contains(q, ignoreCase = true) }
        }
        .stateIn(
            scope = viewModelScope,
            started = SharingStarted.WhileSubscribed(5_000),
            initialValue = emptyList(),
        )
}
Focused example: keep your generated package and theme. Add the shown APIs to your Compose project using Android Studio imports.

Tip

stateIn(..., SharingStarted.WhileSubscribed(5_000), initialValue) is the standard recipe for exposing a derived flow as UI state. WhileSubscribed(5000) keeps the upstream alive for 5 seconds after the last collector leaves — long enough to survive a rotation, short enough to stop work when the user really leaves.

Collecting safely

For renderable state in Compose, use collectAsStateWithLifecycle() — it collects at the configured active lifecycle state and gives you a value that triggers recomposition on change:

SearchScreen.kt
@Composable
fun SearchScreen(viewModel: SearchViewModel) {
    val contacts by viewModel.uiState.collectAsStateWithLifecycle()

    LazyColumn {
        items(contacts, key = { it.id }) { ContactRow(it) }
    }
}
Focused example: keep your generated package and theme. Add the shown APIs to your Compose project using Android Studio imports.

That's the whole reactive loop: the database emits new contacts → the pipeline re-filters → the StateFlow updates → the list recomposes. You wrote no manual refresh anywhere.

Practice: one small working feature

Expose a list as StateFlow and display it using lifecycle-aware collection.

Check your result

Adding a record produces a new list and the screen reflects it without a manual refresh.

Remember

StateFlow represents current state and may conflate rapid updates. It is not a log of every event.

Recap & quick check

Key takeaways

  • Flow models a stream of values over time — how Room and DataStore deliver data.
  • Cold producers run per collector; Flow can also represent hot streams. StateFlow holds current state; SharedFlow has configurable replay.
  • Expose renderable state as StateFlow; replay-zero SharedFlow signals can be lost without active collectors.
  • Transform with map/filter and merge streams with combine; convert to state with stateIn.
  • Collect renderable state with collectAsStateWithLifecycle; use deliberate lifecycle/effect handling for other collection needs.

Quick check

1. What is a cold Flow?

2. Which type best fits UI state a screen renders?

3. You want a filtered list from a data stream plus a query stream. Use…

4. What does stateIn(..., WhileSubscribed(5000)) do?

5. What happens to a default replay-zero SharedFlow emission when no collector is active?

You can stream data reactively. Now let's persist it — starting with simple settings via DataStore.