StateFlow and SharedFlow

Learn StateFlow and SharedFlow in Android to master conflation, replay, and buffering rules while correctly using stateIn and shareIn in ViewModels. About 25 minutes.

Why it matters

  • StateFlow and SharedFlow are the two hot-flow types every Android ViewModel exposes; picking the wrong one causes lost events, stale values replayed to a new screen, or upstream work that never stops.
  • Interviewers at senior level ask you to explain conflation, equality-based skipping, what update makes atomic, and the SharingStarted strategies without looking at docs.
  • Assuming emit waits for a collector, or ignoring the result of tryEmit, are common causes of "the snackbar sometimes doesn't show" bugs.
  • The stateIn / shareIn + WhileSubscribed(5_000) pattern is the idiomatic way to turn a cold repository flow into ViewModel state; Eagerly keeps the upstream running while nobody is looking.

The simple explanation

  • StateFlow is a digital thermostat on the wall. It always shows the current temperature. Walk in at any moment and you see the latest reading; you never see the 200 readings that happened while you were in the kitchen.
  • SharedFlow is a live PA announcement in a building. If you are not in the room when it plays, you miss it (replay = 0). If the system records the last three announcements, a late arrival hears those three (replay = 3).
  • Conflation means the thermostat overwrites the display with each new reading. There is no queue of old temperatures.
  • update is like two people editing the same whiteboard number: each one checks the number has not changed since they read it before writing, so neither edit is lost.
  • WhileSubscribed(5_000) is the building's policy: keep the PA system running for 5 seconds after the last person leaves the room, then power it down to save electricity.

StateFlow and SharedFlow are the two hot flow types in kotlinx.coroutines.flow: they exist and hold values independently of collectors, and a collector never completes them.

StateFlow always holds a value. Create it with MutableStateFlow(initial). It is conflated: a slow collector skips intermediate values and gets the latest one. It also skips a new value that is equal (==) to the current one, so it behaves as if distinctUntilChanged were built in. A new collector gets the current value immediately (replay is fixed at 1). Setting value is thread-safe, but value = value + 1 is a read then a write, and two concurrent callers can lose an update. update { } retries with compareAndSet until its read-modify-write succeeds. Expose the read-only side with asStateFlow().

SharedFlow has no initial value. You configure replay (how many past values a new collector gets), extraBufferCapacity (extra room for slow collectors) and onBufferOverflow. A value emitted while there are no subscribers is not buffered: it is lost, except for what goes into the replay cache. With subscribers, emit suspends only when the buffer is full because a collector is slow. tryEmit never suspends and returns false when it would have to. Expose the read-only side with asSharedFlow().

StateFlowSharedFlow
Initial valuerequirednone
Equal valuesskippeddelivered
Slow collectorgets the latest value (conflated)emitter suspends by default; onBufferOverflow can drop instead
Replayfixed 1configurable, default 0
No subscribersvalue is still storedvalue is lost (except the replay cache)
Atomic read-modify-writeupdate { }not applicable
Typical useUI state, settingsbroadcasts to every active collector

In Android the standard bridge is flow.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), initial). The upstream starts with the first subscriber and stops 5 s after the last one leaves, so a rotation (where the UI resubscribes within a second or so) does not restart it, but going to the background does stop it. In Compose, collect a StateFlow with collectAsStateWithLifecycle().

A late collector still gets the current state
A late collector still gets the current state The ViewModel creates a MutableStateFlow with Loading, then sets it to Loaded. A collector starts only after that and immediately receives Loaded, the current value. When the ViewModel sets a new value, the collector receives it too. Holds Loaded as the current value MutableStateFlow(Loading) value = Loaded collect Loaded, AT ONCE value = Refreshed Refreshed ViewModel sets the value StateFlow holds one value Late collector joins later
StateFlow always holds one current value, so a collector that starts late receives it at once, then every later update.

Notes

  • StateFlow always has a value, is conflated, and skips values equal to the current one. SharedFlow has no initial value and delivers every value, including duplicates, to every active collector.
  • StateFlow compares with equals. Use immutable data classes for state: mutating a list in place and setting the same instance again emits nothing.
  • Setting value is thread-safe. update { it + 1 } makes the whole read-modify-write atomic; value = value + 1 can lose an update when two coroutines run it at the same time.
  • A MutableSharedFlow with no subscribers drops emitted values (apart from the replay cache). emit returns at once and tryEmit returns true, so nothing tells you the event was lost.
  • With subscribers, emit suspends when the buffer is full; tryEmit returns false instead. With the default MutableSharedFlow() (no buffer), tryEmit returns false whenever there is a subscriber.
  • asStateFlow() and asSharedFlow() return the read-only interface. Expose only the read-only type from a ViewModel so callers cannot mutate internal state.
  • SharingStarted.WhileSubscribed(5_000) starts the upstream on the first subscriber and stops it 5 s after the last one leaves. Eagerly starts immediately and never stops; Lazily starts on the first subscriber and never stops.
  • MutableSharedFlow(replay = 1) is not the same as StateFlow: it has no initial value, does not skip equal values, and by default makes the emitter wait for a slow collector instead of dropping old values.
  • stateIn and shareIn take a CoroutineScope, usually viewModelScope, in which they collect the upstream. The sharing stops when that scope is cancelled.
  • For one-off UI events, Android's architecture guidance prefers state (for example a userMessage field that the UI clears after showing it). If you use a stream, a Channel exposed with receiveAsFlow() keeps events until a collector takes them, unlike a SharedFlow.

Code example

This ViewModel exposes a StateFlow for the current user (UI state) and a Channel-backed flow for one-off messages, so a message sent while the screen is not collecting is kept, not lost.

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
 
data class User(val id: String, val name: String)
 
interface UserRepository {
    suspend fun fetchUser(id: String): User // main-safe
}
 
sealed interface UiEvent {
    data class ShowToast(val msg: String) : UiEvent
}
 
class UserViewModel(private val repo: UserRepository) : ViewModel() {
 
    // StateFlow: always holds a value, conflated, skips equal values
    private val _user = MutableStateFlow<User?>(null)
    val user: StateFlow<User?> = _user.asStateFlow()
 
    // Channel: buffers events until the UI collects them
    private val _events = Channel<UiEvent>(Channel.BUFFERED)
    val events: Flow<UiEvent> = _events.receiveAsFlow()
 
    fun loadUser(id: String) {
        viewModelScope.launch {
            _user.value = repo.fetchUser(id) // a plain write is fine: it does not depend on the old value
        }
    }
 
    fun rename(newName: String) {
        // read-modify-write: update retries if another coroutine changed the value meanwhile
        _user.update { current -> current?.copy(name = newName) }
        _events.trySend(UiEvent.ShowToast("Saved"))
    }
}
  • _user.value = ... is enough when the new value does not depend on the old one. update is for changes computed from the current value, like copy(name = ...).
  • Channel.BUFFERED holds up to 64 events by default. trySend on a buffered channel succeeds unless the buffer is full.
  • A MutableSharedFlow<UiEvent>() here would drop the toast if the screen was not collecting at that moment (for example during a rotation). A channel keeps it, but each event goes to one collector, so use it only when there is a single consumer.
  • The public properties are read-only types. The MutableStateFlow and the Channel stay private so other code cannot write to them.

Run the idea in plain Kotlin

Conflation and equality on a StateFlow, a lost event on a SharedFlow, and replay for a late collector.

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

fun main() = runBlocking {
  val state = MutableStateFlow(0)
  for (i in 1..5) state.value = i
  println("StateFlow, late collector gets: " + state.first())

  val stateJob = launch { state.collect { println("  collected " + it) } }
  yield()           // the collector starts and gets the current value, 5
  state.value = 5   // equal to the current value: skipped
  state.value = 6
  state.value = 7   // the collector has not run since 6 was set, so 6 is overwritten
  yield()
  stateJob.cancel()

  val events = MutableSharedFlow<String>()   // replay = 0, no buffer
  events.emit("lost")                        // no subscribers: returns at once, value dropped
  val eventJob = launch { events.collect { println("  event " + it) } }
  yield()
  events.emit("shown")
  yield()
  eventJob.cancel()

  val replayed = MutableSharedFlow<String>(replay = 2)
  replayed.emit("a")
  replayed.emit("b")
  replayed.emit("c")
  println("replay = 2, late collector gets: " + replayed.take(2).toList())
}

Expected output:

StateFlow, late collector gets: 5
  collected 5
  collected 7
  event shown
replay = 2, late collector gets: [b, c]

In production

Silently dropped 'Payment received' snackbar
  • Users reported that a 'Payment received' snackbar sometimes never appeared after a successful transfer.
  • The ViewModel sent it through MutableSharedFlow<UiEvent>() and the screen collected it with repeatOnLifecycle(STARTED).
  • When the result arrived while the app was in the background or mid-rotation, there was no subscriber. emit returned normally and the event was dropped with no log or error.
The fix
  • Reproduced by sending the app to the background before the fake payment call returned.
  • Moved the message into UI state (paymentMessage: String? in the screen's UiState). The screen shows it and calls viewModel.onMessageShown(), which clears it.
  • For another screen with a single collector, used Channel(Channel.BUFFERED).receiveAsFlow(), which keeps events until they are collected.
  • Added a unit test that sends the event before any collector subscribes and asserts the collector still receives it.
Unread badge kept working in the background
  • Battery dashboards showed more background CPU after a release that added a live 'unread count' badge.
  • The team used stateIn(viewModelScope, SharingStarted.Eagerly, 0) for a Room Flow<Int> of unread messages.
  • Eagerly never stops the upstream. The screen's ViewModel stayed alive on the back stack, so every time a background sync wrote messages, Room re-ran the query and the badge was recomputed, with no one looking.
The fix
  • Confirmed by logging in onEach before stateIn and putting the app in the background during a sync.
  • Switched to SharingStarted.WhileSubscribed(5_000) and collected with collectAsStateWithLifecycle(), so the query stops 5 s after the screen stops.
  • Added a test with runTest that cancels the collector, advances virtual time by 5 s and asserts the upstream completed.

Common mistakes

  • Using value = value + 1 instead of update. Two coroutines can read the same old value and both write old + 1, so one increment is lost. update { it + 1 } retries with compareAndSet and never loses an update.
  • Treating MutableSharedFlow(replay = 1) as a drop-in for StateFlow. It has no initial value, does not skip equal values, and makes the emitter wait for a slow collector. Use MutableStateFlow for state.
  • Expecting a SharedFlow to hold events for a future collector. With no subscriber, an emitted value is lost (except the replay cache), and neither emit nor tryEmit reports it. Model the event as state, or use a Channel for a single consumer.
  • Calling tryEmit and ignoring the returned Boolean. With subscribers and a full buffer, tryEmit returns false and the value is dropped. With the default MutableSharedFlow(), that is every call while someone is collecting. Check the result, give it extraBufferCapacity, or use emit from a coroutine.
  • Using SharingStarted.Eagerly for per-screen state. Eagerly starts the upstream immediately and never stops it, so it runs as long as the ViewModel lives, even in the background. Use WhileSubscribed(5_000).
  • Mutating the state object in place. list.add(item) followed by _state.value = list sets an equal (the same) instance, so StateFlow emits nothing. Build a new value: _state.update { it + item }.
  • Exposing MutableStateFlow or MutableSharedFlow from a ViewModel. Any caller can then write to it, breaking encapsulation. Expose StateFlow / SharedFlow via asStateFlow() / asSharedFlow() and keep the mutable one private.

Interview questions

Answer out loud first. Then reveal the answer and compare it at each depth.

“When would you choose StateFlow over SharedFlow, and vice versa?”

“Explain what SharingStarted.WhileSubscribed(5_000) does and why the 5-second window exists.”

“What is the difference between emit and tryEmit on a MutableSharedFlow?”

“How do you collect a StateFlow and a SharedFlow in a Compose screen without collecting in the wrong lifecycle state?”

Quiz

What does a new collector of a StateFlow receive first?

What happens when you call emit on a MutableSharedFlow(replay = 0, extraBufferCapacity = 0) and no one is collecting?

Two coroutines run counter.update { it + 1 } at the same time on a MutableStateFlow(0). What is the value afterwards?

What does SharingStarted.WhileSubscribed(5_000) control?

0 of 4 answered

Mini task

Build a counter ViewModel with StateFlow and an event

Goal: Create a CounterViewModel that exposes a StateFlow<Int> for the current count and a flow of 'reset' events, then write two unit tests.

  1. Create a new CounterViewModel class that extends ViewModel.
  2. Declare private val _count = MutableStateFlow(0) and expose val count: StateFlow<Int> = _count.asStateFlow().
  3. Declare private val _events = Channel<String>(Channel.BUFFERED) and expose val events: Flow<String> = _events.receiveAsFlow().
  4. Add fun increment() that calls _count.update { it + 1 }.
  5. Add fun reset() that sets _count.value = 0 and then calls _events.send("reset") inside viewModelScope.launch.
  6. In the test class, call Dispatchers.setMain(StandardTestDispatcher()) before each test and Dispatchers.resetMain() after.
  7. Write a test increment_updates_state_flow: in runTest, collect count into a list with backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)), call increment() three times, and assert the list is [0, 1, 2, 3].
  8. Write a test reset_emits_event_without_collector: call reset() before anyone collects, run advanceUntilIdle(), then assert events.first() is "reset".
  9. Bonus: change _events to MutableSharedFlow<String>() and watch test 8 time out, because the event was dropped before anyone collected.

Done condition: Both tests pass with runTest. The ViewModel's public API exposes no Mutable types or Channel. increment uses update, not value = value + 1.

Next: Flow operators