State and architecture cheat sheet

Revise Android state and architecture: StateFlow, asStateFlow, update, stateIn, SavedStateHandle, MVI reducer, and one-off event patterns in ViewModel.

Key ideas

  1. Expose StateFlow<T> via asStateFlow(); keep MutableStateFlow private so no caller can set .value and bypass ViewModel logic.
  2. Always write state with update { it.copy(...) }; it is atomic via compareAndSet. Plain value = loses concurrent writes.
  3. One immutable data class or sealed UiState per screen. Multiple StateFlow fields let a render mix a new value from one flow with an old value from another.
  4. Events go up (UI calls ViewModel methods); state goes down (StateFlow to UI). The ViewModel never holds a View, Activity, or Composable reference.
  5. One-off events: a nullable field in UiState that the UI reads, acts on, then clears by calling consumeEvent(). Without clearing, StateFlow replays it after rotation.
  6. 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.
  7. MVI replaces many ViewModel methods with one onIntent(intent) entry point and a pure reduce(state, intent) function. The reducer has no side effects, no coroutines, no else branch.
  8. SavedStateHandle survives process death only (not user dismiss or force-stop). Store ids and queries, not large lists or bitmaps, because it is saved to a Bundle.
  9. Collect in Compose with collectAsStateWithLifecycle(); in a Fragment wrap in viewLifecycleOwner.repeatOnLifecycle(STARTED). Never collect in GlobalScope.
  10. 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-populated SavedStateHandle.

APIs at a glance

API or termUse 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.
SavedStateHandleRestores 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.
runTestTest 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(...) } over value = for every state write; update is atomic, value = is not.
  • Never expose MutableStateFlow publicly; always convert with asStateFlow() so the UI is read-only.
  • Never mutate a List or Map inside UiState; StateFlow skips a value that equals the current one, so the UI never re-renders.
  • Prefer one UiState object per screen over multiple independent StateFlow fields to avoid mixed old-and-new renders.
  • Never wrap suspend calls in runCatching inside viewModelScope; it swallows CancellationException and reports a bogus error. Use try/catch and rethrow CancellationException.
  • Prefer WhileSubscribed(5_000) over WhileSubscribed() so a rotation does not stop and restart the upstream.

Gotchas

  • Exposing MutableStateFlow as a public property. Any caller can set .value directly, bypassing ViewModel logic and creating inconsistent state. Fix: expose StateFlow via asStateFlow() 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 via compareAndSet.
  • Storing a one-off event in UiState and never clearing it. StateFlow gives its latest value to every new collector, so the snackbar or navigation fires again after rotation. Fix: the UI calls consumeEvent() (or onMessageShown()) to set the field back to null.
  • Using WhileSubscribed() without a timeout. The default stopTimeoutMillis is 0, so the upstream stops and restarts on every rotation, repeating network calls or queries. Fix: use WhileSubscribed(5_000).
  • Storing large lists or bitmaps in SavedStateHandle. It is serialised into a Bundle and causes TransactionTooLargeException when 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 or collectAsStateWithLifecycle() 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.

Go deeper