ViewModel and UI state
Why it matters
- Many UI bugs in Android come from state that is mutated in two places, collected in a lifecycle-unaware way, or split across several fields that can disagree.
- Interviewers at senior level ask you to draw the data flow for a screen and explain how a one-off event (snackbar, navigation) can be lost or shown twice.
- A single StateFlow of one immutable type is a small, clear contract that makes a screen testable without a device.
- Choosing between a flat data class and a sealed hierarchy is a design decision that shows up in code reviews and architecture discussions.
The simple explanation
- A ViewModel is the conductor of a small orchestra: it holds the score (state) and tells every musician (UI component) what to play.
The ViewModel owns one private MutableStateFlow of an immutable data class. The UI collects the public StateFlow (returned by asStateFlow()) and renders. User actions call methods on the ViewModel; each method calls update on the private flow. update reads the current value, applies the lambda and writes the result with compareAndSet, retrying if another coroutine changed the value in between, so no change is lost.
The ViewModel survives configuration changes such as rotation: the new Activity or Fragment gets the same instance, with its state still in memory. viewModelScope is cancelled and onCleared() runs only when the owner is finished for good (the screen is popped or the Activity finishes), not on rotation. Process death destroys the ViewModel like everything else; that is what SavedStateHandle is for.
| Shape | When to use | Cost |
|---|---|---|
Flat data class | A few independent fields | Can hold contradictory values (e.g. isLoading = true and error != null) |
Sealed interface (Loading, Success, Error) | Mutually exclusive phases | More boilerplate; harder to combine independent sub-states |
MVI reducer (State, Intent) -> State | Many intents, large screens, need a single testable transition | Reducer grows; the intent hierarchy can become large |
stateIn(scope, SharingStarted.WhileSubscribed(5_000), initial) turns a cold Flow into a hot StateFlow. The upstream keeps running for 5 s after the last collector leaves, so a rotation does not restart it, while going to the background stops it.
Events go up (the UI calls ViewModel methods); state goes down (the UI collects the StateFlow). The UI never writes to the flow. For one-off events (snackbar, navigation), Android's architecture guidance is to model them as state: a nullable field the UI reads and then clears by calling the ViewModel. A SharedFlow with replay = 0 loses an event emitted while nobody collects. A Channel keeps it until it is received, but an event can still be lost if the collector is cancelled right after receiving it. A state field that the UI explicitly clears cannot be lost and is not shown twice.
Testing: construct the ViewModel with a fake repository, set Dispatchers.setMain to a test dispatcher (because viewModelScope uses Dispatchers.Main.immediate), call methods and assert on state.value or on collected values. For SavedStateHandle, pass SavedStateHandle(mapOf(...)) with the values you want to restore and verify the ViewModel reads them.
Notes
- Expose
StateFlow<T>to the UI, neverMutableStateFlow<T>. UseasStateFlow()so the UI cannot set.valueor callupdate. MutableStateFlow.update { it.copy(...) }makes a read-modify-write atomic._state.value = _state.value.copy(...)can lose a concurrent change.- Prefer one immutable
data classor one sealed hierarchy as the state type. Several independentStateFlowfields force the UI to combine them, and the screen can render a mix of new and old values. stateIn(scope, SharingStarted.WhileSubscribed(5_000), initial)keeps the upstream running 5 s after the last collector leaves.WhileSubscribed()without an argument stops it immediately, so every rotation restarts the upstream.- Events go up, state goes down. The UI calls ViewModel methods; the ViewModel never holds a reference to a View, Activity or Composable.
- For one-off events, a nullable field in state that the UI reads and then clears (for example
onMessageShown()) is the pattern the Android architecture guide recommends. - A flat
data classis fine for independent fields. Switch to a sealed type when states are mutually exclusive (Loading vs Success vs Error) so awhenmust handle every case. Mixing is common: a data class with a sealedcontentfield. - MVI replaces many ViewModel methods with one
onIntent(intent)entry point and a pure reducer(State, Intent) -> State. The benefit is a single testable transition function; the cost is a growing intent hierarchy. - In tests, construct the ViewModel with a fake repository and, if needed, a pre-populated
SavedStateHandle. UserunTestand a test Main dispatcher. No Activity or Fragment is needed. - A large list in ViewModel state is fine: it lives in memory and
copy()shares the list reference. Do not put large data inSavedStateHandle, which is saved to a Bundle and is limited in size.
Code example
This ViewModel exposes one immutable ScreenState as a StateFlow. A loadItems method updates the flow with update, showing the loading, success and error paths in one place.
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
interface Repository {
suspend fun fetchItems(): List<String> // main-safe
}
data class ScreenState(
val items: List<String> = emptyList(),
val isLoading: Boolean = false,
val error: String? = null,
)
class ScreenViewModel(
private val repository: Repository,
) : ViewModel() {
// private mutable, public read-only
private val _state = MutableStateFlow(ScreenState())
val state: StateFlow<ScreenState> = _state.asStateFlow()
init {
loadItems()
}
fun loadItems() {
viewModelScope.launch {
_state.update { it.copy(isLoading = true, error = null) }
try {
val items = repository.fetchItems()
_state.update { it.copy(items = items, isLoading = false) }
} catch (e: CancellationException) {
throw e // the ViewModel was cleared: do not report it as an error
} catch (e: Exception) {
_state.update {
it.copy(isLoading = false, error = e.message ?: "Unknown")
}
}
}
}
fun retry() = loadItems()
}_stateis private; the UI only seesstate: StateFlow<ScreenState>, so it cannot bypass the ViewModel.- Loading starts in
init, so it runs once per ViewModel, not again after a rotation. CancellationExceptionis rethrown. A plaincatch (e: Exception)would also catch the cancellation that happens when the ViewModel is cleared.- On error, the old
itemsstay in the state, so the screen can keep showing them next to the message.
Run the idea in plain Kotlin
The same state holder with a fake repository and a collector that "renders" each state. It succeeds once, then fails.
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
data class ScreenState(
val items: List<String> = emptyList(),
val isLoading: Boolean = false,
val error: String? = null,
)
class FakeRepository(var fail: Boolean = false) {
suspend fun fetchItems(): List<String> {
delay(100)
if (fail) throw IllegalStateException("offline")
return listOf("Kotlin", "Compose")
}
}
class ScreenHolder(private val scope: CoroutineScope, private val repository: FakeRepository) {
private val _state = MutableStateFlow(ScreenState())
val state: StateFlow<ScreenState> = _state.asStateFlow()
fun loadItems() {
scope.launch {
_state.update { it.copy(isLoading = true, error = null) }
try {
val items = repository.fetchItems()
_state.update { it.copy(items = items, isLoading = false) }
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
_state.update { it.copy(isLoading = false, error = e.message) }
}
}
}
}
fun main() = runBlocking {
val repository = FakeRepository()
val holder = ScreenHolder(this, repository)
val ui = launch {
holder.state.collect { s ->
println("render: loading=" + s.isLoading + " items=" + s.items + " error=" + s.error)
}
}
yield()
holder.loadItems()
delay(200)
repository.fail = true
holder.loadItems()
delay(200)
ui.cancel()
}Expected output:
render: loading=false items=[] error=null
render: loading=true items=[] error=null
render: loading=false items=[Kotlin, Compose] error=null
render: loading=true items=[Kotlin, Compose] error=null
render: loading=false items=[Kotlin, Compose] error=offline
In production
- A Fragment called
viewModel._state.value = ScreenState()to clear the list when the user pressed "Clear". - The ViewModel's own
loadItemscoroutine was still in flight and wrote its result afterwards, so the cleared list came back a moment later. - The bug was hard to find because the write happened in the Fragment, so searching the ViewModel for state changes showed nothing.
- The team made
_stateprivate and exposed onlyStateFlowviaasStateFlow(). - The Fragment now calls
viewModel.clearItems(), which cancels the in-flight load job and then calls_state.update { ScreenState() }, so all writes go through the ViewModel. - A custom lint check now flags any public
MutableStateFlowproperty in a ViewModel.
- To survive process death, the screen also put its whole
List<FullItem>(Parcelable) intoSavedStateHandle. - When users with long lists sent the app to the background, it crashed with
TransactionTooLargeException, because saved state is sent to the system in a Bundle and the Binder transaction buffer is about 1 MB, shared by the process. - The crash appeared in Crashlytics only for heavy users, so it slipped through QA.
SavedStateHandlenow stores only the search query, the selected item id and the scroll position.- The list is reloaded from the Room cache after process death, so the screen shows data almost immediately.
- Added the TooLargeTool library to debug builds to log saved-state sizes per screen.
Common mistakes
- Exposing MutableStateFlow as a public property. Any caller can set
.valuedirectly, bypassing the ViewModel's logic and creating inconsistent state. ExposeStateFlowviaasStateFlow()and keep the mutable flow private. - Multiple StateFlow fields for one screen. The UI must combine several flows, and a render can mix a new value from one flow with an old value from another. Use one state object so every emission is a consistent snapshot.
- Reading value and then writing value.
val old = _state.value; _state.value = old.copy(...)is not atomic. Two coroutines can read the sameold, and the second write overwrites the first. Use_state.update { it.copy(...) }. - Storing a one-off event in state and never clearing it. The snackbar shows again every time the UI re-collects, for example after rotation. The UI must call a method such as
onMessageShown()that sets the field back tonull. - Using WhileSubscribed() without a timeout. The default
stopTimeoutMillisis 0, so the upstream stops and restarts on every rotation, repeating network calls or queries. UseWhileSubscribed(5_000). - Collecting state in a lifecycle-unaware scope. Collecting in
GlobalScope, a plainlifecycleScope.launchor a Fragment's own lifecycle keeps collecting in the background or after the view is destroyed. UseviewLifecycleOwner.repeatOnLifecycle(STARTED)in Fragments orcollectAsStateWithLifecycle()in Compose.
Interview questions
Answer out loud first. Then reveal the answer and compare it at each depth.
“Why do you expose StateFlow instead of MutableStateFlow from a ViewModel?”
“When would you choose a sealed class over a flat data class for UI state?”
“How does stateIn with WhileSubscribed work, and why does the timeout matter?”
“How do you handle a one-off event like showing a snackbar without losing it or showing it twice?”
Quiz
What does MutableStateFlow.update do that a plain value assignment does not?
What happens if you call stateIn with SharingStarted.WhileSubscribed() and no timeout argument?
A screen's ViewModel holds a 5,000-item list in its UI state StateFlow. What happens to that list when the user rotates the device?
Which approach does the Android architecture guidance recommend for a one-off event like a snackbar that must not be lost or shown twice?
0 of 4 answered
Mini task
15-minute exercise: add loading and error to an existing screen
-
Open the
ScreenViewModelin your project (or create a new one). Define adata class ScreenState(val items: List<String> = emptyList(), val isLoading: Boolean = false, val error: String? = null). Keep theMutableStateFlowprivate and exposeStateFlowviaasStateFlow(). -
Add a
loadItems()method that setsisLoading = true, calls a repository, and on success setsitemsandisLoading = false. On exception, seterrorandisLoading = false, and rethrowCancellationException. Use_state.update { it.copy(...) }for every write. -
In the Composable, collect the
StateFlowwithcollectAsStateWithLifecycle(); in a Fragment, useviewLifecycleOwner.lifecycleScope.launchwithviewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED). Render a progress indicator whenisLoadingis true, a list whenitemsis non-empty, and an error message with a retry button whenerroris non-null. -
Add a
retry()method that callsloadItems(). Wire the retry button to it. -
Write a unit test: set
Dispatchers.setMain(StandardTestDispatcher()), construct the ViewModel with a fake repository that returns two items, callloadItems()insiderunTest, runadvanceUntilIdle(), and assert thatstate.valuehasisLoading = falseand two items. Then change the fake to throw and asserterroris non-null.
Done condition: the screen shows a spinner, then the list, then an error with a working retry button. The unit test passes for both the success and failure paths. No MutableStateFlow is visible outside the ViewModel.