MVVM in practice
Why it matters
- Stale or lost UI state after rotation is a common source of visible UI defects in production Android apps.
- Interviewers probe StateFlow vs LiveData, the atomic update pattern, and lifecycle-aware collection; getting these wrong signals a mid-level gap.
- Choosing MVVM over MVI (or vice versa) affects testability and team velocity; you must justify the choice, not just name it.
- Collecting a flow in the wrong scope keeps updating a destroyed view or leaks it, and it is hard to reproduce in QA.
The simple explanation
- Think of a restaurant kitchen (ViewModel) and a dining table (UI).
- The kitchen holds one order ticket (UiState) that shows the current status.
- The waiter brings new requests UP to the kitchen (events as function calls).
- The kitchen rewrites the ticket and the table sees the new status DOWN (StateFlow emission).
- The ticket is replaced, never edited in place (immutable data class).
- If the table is cleared (view destroyed), the kitchen keeps the ticket (ViewModel survives rotation).
In MVVM the ViewModel owns a single StateFlow<UiState> that the UI collects. State flows down; user actions flow up as function calls on the ViewModel. UiState is an immutable data class (or sealed interface) with fields like isLoading, items, error.
The ViewModel wraps a MutableStateFlow privately and exposes a read-only StateFlow via asStateFlow(). Every write goes through the update { } extension, which makes the read-modify-write atomic: it reads the current value, applies the lambda and writes with compareAndSet, retrying if another coroutine changed the value in between. Using _state.value = ... is not atomic and can lose a concurrent update.
On the UI side, Compose uses collectAsStateWithLifecycle() from lifecycle-runtime-compose. In a Fragment you wrap collection in repeatOnLifecycle(Lifecycle.State.STARTED) inside viewLifecycleOwner.lifecycleScope. Collecting in the Fragment's own lifecycleScope keeps running after onDestroyView, so it can touch a destroyed view binding (a crash or a leak) and keeps working in the background.
For a derived or long-running cold flow, stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), initial) converts it to a hot StateFlow. The 5-second grace period prevents upstream restarts when the UI briefly loses and regains a collector during a configuration change.
| Choice | Flat data class | Sealed interface |
|---|---|---|
| Update | copy() is trivial | Must rebuild the variant |
| UI rendering | Check booleans / nulls | Exhaustive when |
| Best for | Independent fields that can change separately | Mutually exclusive modes (Loading, Content, Error) |
MVVM uses state plus ViewModel methods. MVI adds a sealed intent type and a pure reducer that maps (state, intent) to the next state. MVI costs more boilerplate but gives one testable transition function and a single place to log every intent. Many teams find MVVM enough for simple CRUD screens and use MVI where many inputs change the same state; this is a team choice, not a rule.
Notes
MutableStateFlowstays private; exposeStateFlowviaasStateFlow(). Any publicMutableStateFlowlets callers bypass ViewModel logic.- Use
update { it.copy(...) }for every write. It is atomic._state.value = ...is a plain set and can lose a concurrent update. UiStateis adata classwithvalfields and read-onlyListorMaptypes.StateFlowskips a value thatequalsthe current one, so mutating a shared list in place produces no emission.- In Compose, collect with
collectAsStateWithLifecycle()fromlifecycle-runtime-compose. In a Fragment, wrap collection inrepeatOnLifecycle(Lifecycle.State.STARTED)insideviewLifecycleOwner.lifecycleScope. stateIn(scope, SharingStarted.WhileSubscribed(5_000), initial)keeps a cold flow alive for 5 s after the last collector leaves, preventing upstream restarts on rotation.- Sealed
UiStategives an exhaustivewhenin the UI; a flatdata classmakescopy()trivial. Pick per screen, not per project. - Events go up as function calls (
fun loadMore()). State goes down asStateFlow. For one-off results (a snackbar message, moving on after a save), Google's guidance is to put them inUiStateand have the UI call the ViewModel (onMessageShown()) to clear them after acting. - Test the ViewModel by injecting a fake repository and asserting on
state.valueor by collecting the flow insiderunTest, withDispatchers.setMainset to a test dispatcher. ForSavedStateHandle, construct the ViewModel with a pre-populated handle. collectAsStateWithLifecycle()stops collecting belowSTARTED(by default). PlaincollectAsState()does not, so it keeps collecting while the app is in the background.- Do not wrap suspend calls in
runCatchinginsideviewModelScope: it also catchesCancellationException. Usetry/catchand rethrowCancellationException.
Code example
This ViewModel exposes one immutable FeedUiState as a StateFlow and updates it atomically with update. The UI collects the flow; user actions call functions on the ViewModel.
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
data class FeedItem(val id: Int, val title: String)
interface FeedRepository {
suspend fun fetchFeed(page: Int, pageSize: Int): List<FeedItem> // main-safe
}
// Immutable UI state: val fields and read-only List
data class FeedUiState(
val isLoading: Boolean = false,
val items: List<FeedItem> = emptyList(),
val error: String? = null,
val hasMore: Boolean = true,
)
class FeedViewModel(private val repo: FeedRepository) : ViewModel() {
// Private mutable, public read-only
private val _state = MutableStateFlow(FeedUiState())
val state: StateFlow<FeedUiState> = _state.asStateFlow()
private var nextPage = 0
init {
loadMore() // runs once per ViewModel, not again after rotation
}
// Events go UP through function calls; state goes DOWN through StateFlow
fun loadMore() {
val current = _state.value
if (current.isLoading || !current.hasMore) return
// Set the flag before launching, so a second tap is ignored
_state.update { it.copy(isLoading = true, error = null) }
viewModelScope.launch {
try {
val page = repo.fetchFeed(page = nextPage, pageSize = PAGE_SIZE)
nextPage++
_state.update {
it.copy(isLoading = false, items = it.items + page, hasMore = page.size == PAGE_SIZE)
}
} catch (e: CancellationException) {
throw e // the ViewModel was cleared: not an error
} catch (e: Exception) {
_state.update { it.copy(isLoading = false, error = e.message ?: "Unknown") }
}
}
}
private companion object {
const val PAGE_SIZE = 20
}
}_stateisprivate; the public surface isStateFlowviaasStateFlow(), so no caller can write to it.- Every write uses
update { it.copy(...) }, so a write from another coroutine is never lost. - The guard and the
isLoading = truewrite both run synchronously on the main thread before the coroutine starts, so two quick calls cannot both start a request. nextPageonly advances on success, so callingloadMore()again after an error retries the same page. On error the loaded items stay on screen.CancellationExceptionis rethrown;runCatchingwould have swallowed it.
Run the idea in plain Kotlin
The same state holder with a fake repository of five posts, two per page. The second tap while loading is ignored, one request fails, and a retry continues from the same page.
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
data class FeedUiState(
val isLoading: Boolean = false,
val items: List<String> = emptyList(),
val error: String? = null,
val hasMore: Boolean = true,
)
class FakeFeedRepository {
var failNext = false
private val all = (1..5).map { "post" + it }
suspend fun fetchFeed(page: Int, pageSize: Int): List<String> {
delay(100)
if (failNext) {
failNext = false
throw IllegalStateException("offline")
}
return all.drop(page * pageSize).take(pageSize)
}
}
class FeedHolder(private val scope: CoroutineScope, private val repo: FakeFeedRepository) {
private val _state = MutableStateFlow(FeedUiState())
val state: StateFlow<FeedUiState> = _state.asStateFlow()
private var nextPage = 0
fun loadMore() {
val current = _state.value
if (current.isLoading || !current.hasMore) {
println("loadMore ignored")
return
}
_state.update { it.copy(isLoading = true, error = null) }
scope.launch {
try {
val page = repo.fetchFeed(nextPage, PAGE_SIZE)
nextPage++
_state.update {
it.copy(isLoading = false, items = it.items + page, hasMore = page.size == PAGE_SIZE)
}
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
_state.update { it.copy(isLoading = false, error = e.message) }
}
}
}
companion object {
const val PAGE_SIZE = 2
}
}
fun main() = runBlocking {
val repo = FakeFeedRepository()
val holder = FeedHolder(this, repo)
val ui = launch {
holder.state.collect { s ->
println("render: loading=" + s.isLoading + " items=" + s.items + " hasMore=" + s.hasMore + " error=" + s.error)
}
}
yield()
holder.loadMore()
holder.loadMore() // second tap while loading
delay(200)
repo.failNext = true
holder.loadMore()
delay(200)
holder.loadMore() // retry the same page
delay(200)
holder.loadMore()
delay(200)
holder.loadMore() // nothing left
ui.cancel()
}Expected output:
render: loading=false items=[] hasMore=true error=null
loadMore ignored
render: loading=true items=[] hasMore=true error=null
render: loading=false items=[post1, post2] hasMore=true error=null
render: loading=true items=[post1, post2] hasMore=true error=null
render: loading=false items=[post1, post2] hasMore=true error=offline
render: loading=true items=[post1, post2] hasMore=true error=null
render: loading=false items=[post1, post2, post3, post4] hasMore=true error=null
render: loading=true items=[post1, post2, post3, post4] hasMore=true error=null
render: loading=false items=[post1, post2, post3, post4, post5] hasMore=false error=null
loadMore ignored
In production
- The Fragment started loading with
lifecycleScope.launch { viewModel.load() }, whereload()was a suspend function that setisLoading = true, fetched, and then set it back tofalse. - Rotating during the request destroyed the Fragment and cancelled its
lifecycleScope, so the coroutine stopped after settingisLoading = trueand never reset it. - The ViewModel survived the rotation, so the new Fragment collected the same
StateFlowwithisLoading = true, and the guardif (isLoading) returnblocked every new load.
- The team made
load()a normal function that launches inviewModelScope, started once frominit. Rotation no longer cancels the request. - The remaining cancellation path (the ViewModel cleared mid-request) resets
isLoadingin afinallyblock. - They added a unit test with a fake repository that never returns: start a load, cancel it, and assert
state.value.isLoading == false.
- Memory profiler showed Fragment instances not being garbage-collected after the user navigated away.
- The Fragment collected the ViewModel's
StateFlowinlifecycleScope(the Fragment's full lifecycle) instead ofviewLifecycleOwner.lifecycleScope. - In a
ViewPager2, the view was destroyed but the Fragment was retained, so the collection kept a reference to the old view.
- The team switched to
repeatOnLifecycle(Lifecycle.State.STARTED)insideviewLifecycleOwner.lifecycleScope. - They set the binding to
nullinonDestroyViewand ran LeakCanary in debug builds, so a retained view now shows up as a leak report. - A code-review checklist item now flags any
lifecycleScope.launchin a Fragment that collects a flow and touches the view.
Common mistakes
- Using _state.value = instead of update. Direct assignment is not atomic. Two coroutines that each read, modify, and write can overwrite each other's fields. Always use
update { it.copy(...) }. - Collecting in GlobalScope or a custom CoroutineScope. Nothing cancels the collection, so it outlives the view and the ViewModel and leaks them. Use
viewModelScopefor the ViewModel side andviewLifecycleOwner.repeatOnLifecycleorcollectAsStateWithLifecyclefor the UI side. - Putting a message in UiState and never clearing it.
StateFlowgives its latest value to every new collector, so after rotation the snackbar shows again. The UI must callonMessageShown()after showing it, and the ViewModel sets the field back tonull. - Mutable fields in UiState. If you
addto aMutableListinside the current state and set the same object again, the new valueequalsthe old one, soStateFlowdoes not emit and the UI never re-renders. Usevalfields and read-only collections, and build new lists withcopy. - Exposing MutableStateFlow publicly. Any caller can write to it, bypassing the ViewModel's logic and invariants. Expose
StateFlowviaasStateFlow()and keep theMutableStateFlowprivate. - Wrapping suspend calls in runCatching.
runCatchingcatches everyThrowable, including theCancellationExceptionthrown whenviewModelScopeis cancelled, so the coroutine reports a bogus error instead of stopping. Usetry/catch, rethrowCancellationException, or catch only the exceptions you expect.
Interview questions
Answer out loud first. Then reveal the answer and compare it at each depth.
“How do you expose UI state from a ViewModel?”
“What happens if you collect a StateFlow in the wrong lifecycle scope?”
“MVVM vs MVI: when would you choose each?”
“How do you test a ViewModel?”
Quiz
Which call makes a read-modify-write on a MutableStateFlow atomic?
What does SharingStarted.WhileSubscribed(5_000) do?
A ViewModel sets userMessage in UiState when a save fails. The UI shows a snackbar but never tells the ViewModel. What happens after a rotation?
Which collection method is lifecycle-aware in Compose?
0 of 4 answered
Mini task
Convert a LiveData ViewModel to StateFlow with update
You have a NewsViewModel that exposes LiveData<NewsUiState>. Convert it to the StateFlow pattern.
- Replace
LiveData<NewsUiState>withMutableStateFlow<NewsUiState>(private) and exposeStateFlow<NewsUiState>viaasStateFlow(). - Replace every
state.value = ...with_state.update { it.copy(...) }. Confirm no direct assignment remains. - In the Composable, replace
observeAsState()withcollectAsStateWithLifecycle()fromlifecycle-runtime-compose. - In any Fragment that collects the flow, wrap the collection in
repeatOnLifecycle(Lifecycle.State.STARTED)insideviewLifecycleOwner.lifecycleScope. - Update the unit tests: replace
InstantTaskExecutorRuleand LiveData observers withrunTest, a rule that callsDispatchers.setMain(StandardTestDispatcher()), and assertions onstate.value. - Rotate the device in the emulator and confirm the UI state is correct after rotation.
Done condition: no LiveData import remains in the ViewModel, all unit tests pass, and the screen shows the correct state after a rotation.