ViewModel and UI state

Learn how to manage Android UI state with ViewModel and StateFlow using immutable data classes, sealed hierarchies, or MVI reducers in Kotlin. About 25 minutes.

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.

ShapeWhen to useCost
Flat data classA few independent fieldsCan hold contradictory values (e.g. isLoading = true and error != null)
Sealed interface (Loading, Success, Error)Mutually exclusive phasesMore boilerplate; harder to combine independent sub-states
MVI reducer (State, Intent) -> StateMany intents, large screens, need a single testable transitionReducer 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.

The ViewModel survives rotation
The ViewModel survives rotation The old screen collects UI state from the ViewModel. The user rotates the phone and the old screen is destroyed, but the ViewModel is not cleared and viewModelScope is not cancelled. The new screen gets the same ViewModel instance and immediately receives the same UI state. Rotation: old screen destroyed Not cleared, viewModelScope keeps running COLLECT UI STATE SAME INSTANCE SAME STATE, NO RELOAD Old screen before rotation ViewModel survives New screen after rotation
The new screen gets the same ViewModel instance, so its state is still there and viewModelScope keeps running.

Notes

  • Expose StateFlow<T> to the UI, never MutableStateFlow<T>. Use asStateFlow() so the UI cannot set .value or call update.
  • MutableStateFlow.update { it.copy(...) } makes a read-modify-write atomic. _state.value = _state.value.copy(...) can lose a concurrent change.
  • Prefer one immutable data class or one sealed hierarchy as the state type. Several independent StateFlow fields 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 class is fine for independent fields. Switch to a sealed type when states are mutually exclusive (Loading vs Success vs Error) so a when must handle every case. Mixing is common: a data class with a sealed content field.
  • 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. Use runTest and 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 in SavedStateHandle, 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()
}
  • _state is private; the UI only sees state: StateFlow<ScreenState>, so it cannot bypass the ViewModel.
  • Loading starts in init, so it runs once per ViewModel, not again after a rotation.
  • CancellationException is rethrown. A plain catch (e: Exception) would also catch the cancellation that happens when the ViewModel is cleared.
  • On error, the old items stay 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

MutableStateFlow leaked to the UI layer
  • A Fragment called viewModel._state.value = ScreenState() to clear the list when the user pressed "Clear".
  • The ViewModel's own loadItems coroutine 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 fix
  • The team made _state private and exposed only StateFlow via asStateFlow().
  • 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 MutableStateFlow property in a ViewModel.
Full list in SavedStateHandle crashed in the background
  • To survive process death, the screen also put its whole List<FullItem> (Parcelable) into SavedStateHandle.
  • 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.
The fix
  • SavedStateHandle now 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 .value directly, bypassing the ViewModel's logic and creating inconsistent state. Expose StateFlow via asStateFlow() 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 same old, 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 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. Use WhileSubscribed(5_000).
  • Collecting state in a lifecycle-unaware scope. Collecting in GlobalScope, a plain lifecycleScope.launch or a Fragment's own lifecycle keeps collecting in the background or after the view is destroyed. Use viewLifecycleOwner.repeatOnLifecycle(STARTED) in Fragments or collectAsStateWithLifecycle() 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

  1. Open the ScreenViewModel in your project (or create a new one). Define a data class ScreenState(val items: List<String> = emptyList(), val isLoading: Boolean = false, val error: String? = null). Keep the MutableStateFlow private and expose StateFlow via asStateFlow().

  2. Add a loadItems() method that sets isLoading = true, calls a repository, and on success sets items and isLoading = false. On exception, set error and isLoading = false, and rethrow CancellationException. Use _state.update { it.copy(...) } for every write.

  3. In the Composable, collect the StateFlow with collectAsStateWithLifecycle(); in a Fragment, use viewLifecycleOwner.lifecycleScope.launch with viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED). Render a progress indicator when isLoading is true, a list when items is non-empty, and an error message with a retry button when error is non-null.

  4. Add a retry() method that calls loadItems(). Wire the retry button to it.

  5. Write a unit test: set Dispatchers.setMain(StandardTestDispatcher()), construct the ViewModel with a fake repository that returns two items, call loadItems() inside runTest, run advanceUntilIdle(), and assert that state.value has isLoading = false and two items. Then change the fake to throw and assert error is 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.

Next: Unidirectional data flow