StateFlow and SharedFlow
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
updatemakes atomic, and theSharingStartedstrategies without looking at docs. - Assuming
emitwaits for a collector, or ignoring the result oftryEmit, 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;Eagerlykeeps 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.
updateis 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().
| StateFlow | SharedFlow | |
|---|---|---|
| Initial value | required | none |
| Equal values | skipped | delivered |
| Slow collector | gets the latest value (conflated) | emitter suspends by default; onBufferOverflow can drop instead |
| Replay | fixed 1 | configurable, default 0 |
| No subscribers | value is still stored | value is lost (except the replay cache) |
| Atomic read-modify-write | update { } | not applicable |
| Typical use | UI state, settings | broadcasts 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().
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
valueis thread-safe.update { it + 1 }makes the whole read-modify-write atomic;value = value + 1can lose an update when two coroutines run it at the same time. - A
MutableSharedFlowwith no subscribers drops emitted values (apart from the replay cache).emitreturns at once andtryEmitreturnstrue, so nothing tells you the event was lost. - With subscribers,
emitsuspends when the buffer is full;tryEmitreturnsfalseinstead. With the defaultMutableSharedFlow()(no buffer),tryEmitreturnsfalsewhenever there is a subscriber. asStateFlow()andasSharedFlow()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.Eagerlystarts immediately and never stops;Lazilystarts 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.stateInandshareIntake aCoroutineScope, usuallyviewModelScope, 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
userMessagefield that the UI clears after showing it). If you use a stream, aChannelexposed withreceiveAsFlow()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.updateis for changes computed from the current value, likecopy(name = ...).Channel.BUFFEREDholds up to 64 events by default.trySendon 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
MutableStateFlowand theChannelstay 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
- 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 withrepeatOnLifecycle(STARTED). - When the result arrived while the app was in the background or mid-rotation, there was no subscriber.
emitreturned normally and the event was dropped with no log or error.
- 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'sUiState). The screen shows it and callsviewModel.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.
- 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 RoomFlow<Int>of unread messages. Eagerlynever 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.
- Confirmed by logging in
onEachbeforestateInand putting the app in the background during a sync. - Switched to
SharingStarted.WhileSubscribed(5_000)and collected withcollectAsStateWithLifecycle(), so the query stops 5 s after the screen stops. - Added a test with
runTestthat 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 withcompareAndSetand 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
MutableStateFlowfor 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
emitnortryEmitreports it. Model the event as state, or use aChannelfor a single consumer. - Calling tryEmit and ignoring the returned Boolean. With subscribers and a full buffer,
tryEmitreturnsfalseand the value is dropped. With the defaultMutableSharedFlow(), that is every call while someone is collecting. Check the result, give itextraBufferCapacity, or useemitfrom a coroutine. - Using SharingStarted.Eagerly for per-screen state.
Eagerlystarts the upstream immediately and never stops it, so it runs as long as the ViewModel lives, even in the background. UseWhileSubscribed(5_000). - Mutating the state object in place.
list.add(item)followed by_state.value = listsets 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/SharedFlowviaasStateFlow()/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.
- Create a new
CounterViewModelclass that extendsViewModel. - Declare
private val _count = MutableStateFlow(0)and exposeval count: StateFlow<Int> = _count.asStateFlow(). - Declare
private val _events = Channel<String>(Channel.BUFFERED)and exposeval events: Flow<String> = _events.receiveAsFlow(). - Add
fun increment()that calls_count.update { it + 1 }. - Add
fun reset()that sets_count.value = 0and then calls_events.send("reset")insideviewModelScope.launch. - In the test class, call
Dispatchers.setMain(StandardTestDispatcher())before each test andDispatchers.resetMain()after. - Write a test
increment_updates_state_flow: inrunTest, collectcountinto a list withbackgroundScope.launch(UnconfinedTestDispatcher(testScheduler)), callincrement()three times, and assert the list is[0, 1, 2, 3]. - Write a test
reset_emits_event_without_collector: callreset()before anyone collects, runadvanceUntilIdle(), then assertevents.first()is"reset". - Bonus: change
_eventstoMutableSharedFlow<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.