State and architecture cheat sheet
Key ideas
- Expose
StateFlow<T>viaasStateFlow(); keepMutableStateFlowprivate so no caller can set.valueand bypass ViewModel logic. - Always write state with
update { it.copy(...) }; it is atomic viacompareAndSet. Plainvalue =loses concurrent writes. - One immutable
data classor sealedUiStateper screen. MultipleStateFlowfields let a render mix a new value from one flow with an old value from another. - Events go up (UI calls ViewModel methods); state goes down (
StateFlowto UI). The ViewModel never holds a View, Activity, or Composable reference. - One-off events: a nullable field in
UiStatethat the UI reads, acts on, then clears by callingconsumeEvent(). Without clearing,StateFlowreplays it after rotation. stateIn(scope, SharingStarted.WhileSubscribed(5_000), initial)keeps a cold upstream alive 5 s after the last collector leaves;WhileSubscribed()with no argument stops it immediately and restarts on every rotation.- MVI replaces many ViewModel methods with one
onIntent(intent)entry point and a purereduce(state, intent)function. The reducer has no side effects, no coroutines, noelsebranch. SavedStateHandlesurvives process death only (not user dismiss or force-stop). Store ids and queries, not large lists or bitmaps, because it is saved to aBundle.- Collect in Compose with
collectAsStateWithLifecycle(); in a Fragment wrap inviewLifecycleOwner.repeatOnLifecycle(STARTED). Never collect inGlobalScope. - Test the reducer as a pure function (no Android runtime). Test the ViewModel with
runTest, a test Main dispatcher, a fake repository, and a pre-populatedSavedStateHandle.
APIs at a glance
| API or term | Use it for |
|---|---|
StateFlow<T> | Read-only flow exposed to the UI; gives its latest value to every new collector. |
MutableStateFlow<T> | Private writable flow inside the ViewModel; never expose it publicly. |
asStateFlow() | Converts a MutableStateFlow to a read-only StateFlow so the UI cannot write state. |
update { } | Atomic read-modify-write on MutableStateFlow via compareAndSet; always prefer over value =. |
stateIn(scope, started, initial) | Turns a cold Flow into a shared hot StateFlow with a defined sharing strategy. |
SharingStarted.WhileSubscribed(5_000) | Keeps the upstream alive 5 s after the last collector leaves, covering a rotation without restarting work. |
SavedStateHandle | Restores small values (ids, queries) after process death; stored in a Bundle, so keep it tiny. |
getStateFlow(key, default) | Bridges a value stored in SavedStateHandle into a StateFlow for the UI stream. |
collectAsStateWithLifecycle() | Compose collector that stops below STARTED; use instead of plain collectAsState(). |
repeatOnLifecycle(STARTED) | Fragment-side collector tied to the view lifecycle; prevents collection after the view is destroyed. |
reduce(state, intent) | Pure MVI transition function; no side effects, no coroutines, no else branch. |
runTest | Test coroutine scope with a test Main dispatcher for ViewModel unit tests; no Activity needed. |
Snippets
ViewModel state with atomic update and CancellationException guard
data class ScreenState(
val items: List<String> = emptyList(),
val isLoading: Boolean = false,
val error: String? = null,
)
interface ItemRepository { suspend fun fetchItems(): List<String> }
class ItemsViewModel(private val repository: ItemRepository) : ViewModel() {
private val _state = MutableStateFlow(ScreenState())
val state: StateFlow<ScreenState> = _state.asStateFlow()
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
} catch (e: Exception) {
_state.update { it.copy(isLoading = false, error = e.message ?: "Unknown") }
}
}
}
}Pure MVI reducer with exhaustive when (no else)
data class ListState(
val isLoading: Boolean = false,
val items: List<String> = emptyList(),
val error: String? = null,
val selectedId: String? = null,
)
sealed interface ListIntent {
data object Load : ListIntent
data object Retry : ListIntent
data class ItemsLoaded(val items: List<String>) : ListIntent
data class LoadFailed(val message: String) : ListIntent
data class Select(val id: String) : ListIntent
data object SelectionHandled : ListIntent
}
fun reduce(state: ListState, intent: ListIntent): ListState = when (intent) {
ListIntent.Load, ListIntent.Retry -> state.copy(isLoading = true, error = null)
is ListIntent.ItemsLoaded -> state.copy(isLoading = false, items = intent.items)
is ListIntent.LoadFailed -> state.copy(isLoading = false, error = intent.message)
is ListIntent.Select -> state.copy(selectedId = intent.id)
ListIntent.SelectionHandled -> state.copy(selectedId = null)
}One-off event: set in state, clear via consumeEvent
sealed interface OneOffEvent { data class ShowToast(val text: String) : OneOffEvent }
data class CartUiState(val items: List<String> = emptyList(), val event: OneOffEvent? = null)
class CartViewModel : ViewModel() {
private val _uiState = MutableStateFlow(CartUiState())
val uiState: StateFlow<CartUiState> = _uiState.asStateFlow()
fun onItemClicked(item: String) {
_uiState.update {
it.copy(items = it.items + item, event = OneOffEvent.ShowToast("Added: $item"))
}
}
fun consumeEvent() {
_uiState.update { it.copy(event = null) }
}
}SavedStateHandle bridged into a StateFlow via stateIn
// Inside a ViewModel with savedStateHandle and repository.search(q): List<String>
private val query: StateFlow<String> = savedStateHandle.getStateFlow("query", "")
val uiState: StateFlow<SearchUiState> = query
.mapLatest { q ->
SearchUiState(query = q, results = if (q.isBlank()) emptyList() else repository.search(q))
}
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5_000),
initialValue = SearchUiState(query = query.value),
)
data class SearchUiState(val query: String = "", val results: List<String> = emptyList())Rules of thumb
- Prefer
update { it.copy(...) }overvalue =for every state write;updateis atomic,value =is not. - Never expose
MutableStateFlowpublicly; always convert withasStateFlow()so the UI is read-only. - Never mutate a
ListorMapinsideUiState;StateFlowskips a value thatequalsthe current one, so the UI never re-renders. - Prefer one
UiStateobject per screen over multiple independentStateFlowfields to avoid mixed old-and-new renders. - Never wrap
suspendcalls inrunCatchinginsideviewModelScope; it swallowsCancellationExceptionand reports a bogus error. Usetry/catchand rethrowCancellationException. - Prefer
WhileSubscribed(5_000)overWhileSubscribed()so a rotation does not stop and restart the upstream.
Gotchas
- Exposing MutableStateFlow as a public property. Any caller can set
.valuedirectly, bypassing ViewModel logic and creating inconsistent state. Fix: exposeStateFlowviaasStateFlow()and keep the mutable flow private. - Using value = instead of update { }. Two coroutines can read the same old value and the second write silently overwrites the first. Fix: always use
update { it.copy(...) }, which retries viacompareAndSet. - Storing a one-off event in UiState and never clearing it.
StateFlowgives its latest value to every new collector, so the snackbar or navigation fires again after rotation. Fix: the UI callsconsumeEvent()(oronMessageShown()) to set 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. Fix: useWhileSubscribed(5_000). - Storing large lists or bitmaps in SavedStateHandle. It is serialised into a
Bundleand causesTransactionTooLargeExceptionwhen the app goes to the background. Fix: store an id or URI and reload the data from a database or file. - Collecting state in GlobalScope or a plain lifecycleScope.launch. Nothing cancels the collection, so it outlives the view and the ViewModel and leaks them. Fix: use
viewLifecycleOwner.repeatOnLifecycle(STARTED)in Fragments orcollectAsStateWithLifecycle()in Compose.
Quick interview answers
Why expose StateFlow instead of MutableStateFlow to the UI?
MutableStateFlow lets any caller set .value or call update, bypassing the ViewModel's logic and invariants. Exposing StateFlow via asStateFlow() enforces the one-writer rule at the type level.
What is the difference between value = and update { } on a MutableStateFlow?
value = is a plain set and is not atomic; two coroutines can read the same old value and the second write overwrites the first. update { } uses compareAndSet internally and retries, so concurrent updates never lose a write.
How do you handle one-off events (snackbar, navigation) in a ViewModel?
Put a nullable field in UiState; the UI reads it, acts, then calls a ViewModel method like consumeEvent() to set it back to null. Without clearing, StateFlow replays the latest value to every new collector, so the event fires again after rotation.
What does SharingStarted.WhileSubscribed(5_000) do and why not use WhileSubscribed()?
WhileSubscribed(5_000) keeps the upstream running for 5 seconds after the last collector leaves, covering a rotation without restarting work. WhileSubscribed() with no argument stops the upstream immediately, so every rotation cancels and restarts it, repeating network calls or queries.
What survives process death and what does not?
SavedStateHandle survives process death but not the user dismissing the task, force-stopping, or clearing data. A Channel or SharedFlow does not survive process death at all; only values written through SavedStateHandle or rememberSaveable are restored.
When would you choose MVI over plain MVVM?
MVI replaces many ViewModel methods with one onIntent entry point and a pure reduce(state, intent) function, giving a single testable transition and an exhaustive when. The cost is extra sealed types and boilerplate, so it is overkill for a two-button screen but valuable when state transitions are complex.