MVI in practice
Why it matters
- Interviewers at senior level ask you to compare MVI and MVVM fairly, not just recite definitions. Knowing the cost of extra types and when MVI is overkill shows judgment.
- One-off results (navigate after save, show a message) are a frequent follow-up: in MVI they live in the state and the UI sends an intent to clear them. Forgetting that intent makes them fire again after rotation.
- A pure reducer is the cheapest unit test in the project: call
reduce(state, intent)and assert the result. No Android, no coroutines, no mocks. - When state is derived from a cold flow with
stateIn,WhileSubscribed(5_000)vsWhileSubscribed(0)decides whether every rotation restarts the upstream (a new query or network call).
The simple explanation
- A restaurant kitchen has one order ticket (state) and one chef (reducer).
- Waiters hand in new orders (intents); the chef updates the ticket.
- The ticket is the only source of truth; no one scribbles notes on napkins.
- A 'bring the dessert' note stays on the ticket until the waiter reports it done; then the chef crosses it off. Nobody repeats it, and nobody forgets it.
- For a tiny menu, the ticket system feels like overhead; for a busy kitchen with many orders arriving at once, it pays off.
MVI stands for Model-View-Intent. The core idea: one immutable UiState data class, a sealed Intent class for user actions, and a pure reduce(state, intent) function that returns the next state. The ViewModel holds a private MutableStateFlow<UiState> and exposes it read-only with asStateFlow().
State down, intents up. The UI collects state and renders it. The UI calls onIntent(intent) for every tap, scroll, or lifecycle event. The reducer decides the next state synchronously. The ViewModel starts side effects (such as a network call) after the reduce, and feeds their results back in as intents (ItemsLoaded, LoadFailed), so the reducer stays the only place state changes. Navigation stays in the UI.
Sealed vs flat UiState. A flat data class (isLoading, error, items) is simpler and works for most screens. A sealed class (Loading, Content(items), Error(msg)) makes illegal states impossible but adds boilerplate. A common approach is to start flat and switch to sealed when you hit a state that should not exist.
Where stateIn fits. If the reducer writes to a MutableStateFlow, asStateFlow() is all you need; calling stateIn on it only adds a second flow and a coroutine. stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), initial) is for state derived from a cold flow, for example combine(_state, repository.observeItems()). On rotation the old UI stops collecting before the new one starts; the 5-second timeout keeps the upstream running across that gap, and stops it when the app stays in the background.
MVVM vs MVI, fairly. MVVM scatters logic across ViewModel methods. MVI centralises it in one reducer. MVI makes transitions easier to test (call reduce() with inputs, assert output) but adds types. For a screen with two buttons MVVM is usually clearer; MVI pays off as more inputs (user, timers, sync) change the same state. Where the line sits is a team decision, not a rule.
| Aspect | MVVM | MVI |
|---|---|---|
| State shape | One immutable UiState (Google's guidance) | One immutable UiState |
| Input | Methods on ViewModel | Sealed Intent |
| Logic location | Scattered in methods | One pure reduce() |
| Test surface | Call methods, assert state (needs a test dispatcher) | Call reduce(state, intent); ViewModel tested separately |
| Cost | Less boilerplate | More types, overkill for small screens |
Notes
- MVI = one immutable
UiStatedata class + sealedIntent+ purereduce(state, intent): UiState. The reducer has no side effects and no coroutines. - Expose the reducer's
MutableStateFlowwithasStateFlow(). UsestateIn(scope, SharingStarted.WhileSubscribed(5_000), initialValue)only when the state is derived from a cold flow; the 5-second grace period covers a rotation. MutableStateFlow.update { }is atomic: it usescompareAndSetinternally, so concurrent updates do not lose writes. Always preferupdateovervalue =.- Sealed
Intentmakes every user action explicit and thewhenin the reducer exhaustive. When the reducer useswhenas an expression without anelsebranch, adding a new intent is a compile error until you handle it. - One-off results (navigate after save, show a message) are fields in
UiState. The UI acts on them and sends an intent such asMessageShown; the reducer clears the field. If nobody clears it, the new UI after rotation (same ViewModel) fires it again. - Flat
UiState(boolean flags, nullable error) is simpler. SealedUiState(Loading,Content,Error) prevents illegal combinations. Many teams start flat and migrate when a state that should not exist becomes hard to prevent. - Test the reducer by calling
reduce(knownState, knownIntent)and asserting the result. No Android runtime, norunTest, no mocks. This is the cheapest test in the project. - MVI costs: extra sealed types, more lines, overkill for a two-button screen. Benefits: single source of truth, exhaustive
when, pure-function testing. Some teams choose per screen; others pick one convention for the whole codebase. stateInwithWhileSubscribed(0)stops the upstream the instant the last collector leaves, so a rotation restarts it and repeats its work. TheStateFlowkeeps its last value, so the UI does not flash; the cost is the repeated query or request.- In the ViewModel, call
reducesynchronously first (the loading flag shows immediately), then launch a coroutine for the side effect and send its result back through the reducer as another intent.
Code example
This shows the MVI pieces for a list screen: a flat UiState, a sealed Intent (user actions plus results of async work), a pure reduce function, and a ViewModel that sends everything through the reducer.
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 UiState(
val items: List<String> = emptyList(),
val isLoading: Boolean = false,
val error: String? = null,
val selectedId: String? = null, // the UI navigates, then sends SelectionHandled
)
sealed interface Intent {
// From the UI
data object Load : Intent
data object Retry : Intent
data class Select(val id: String) : Intent
data object SelectionHandled : Intent
// From the ViewModel: results of async work
data class ItemsLoaded(val items: List<String>) : Intent
data class LoadFailed(val message: String) : Intent
}
// Pure function: no side effects, no coroutines, no else branch
fun reduce(state: UiState, intent: Intent): UiState = when (intent) {
Intent.Load, Intent.Retry -> state.copy(isLoading = true, error = null)
is Intent.ItemsLoaded -> state.copy(isLoading = false, items = intent.items)
is Intent.LoadFailed -> state.copy(isLoading = false, error = intent.message)
is Intent.Select -> state.copy(selectedId = intent.id)
Intent.SelectionHandled -> state.copy(selectedId = null)
}
class ListViewModel(
private val fetch: suspend () -> List<String>, // main-safe
) : ViewModel() {
private val _state = MutableStateFlow(UiState())
val state: StateFlow<UiState> = _state.asStateFlow()
fun onIntent(intent: Intent) {
_state.update { reduce(it, intent) } // every change goes through the reducer
when (intent) {
Intent.Load, Intent.Retry -> load()
else -> Unit // no side effect for the other intents
}
}
private fun load() {
viewModelScope.launch {
val result = try {
Intent.ItemsLoaded(fetch())
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
Intent.LoadFailed(e.message ?: "Unknown")
}
onIntent(result) // the result is just another input to the reducer
}
}
}reduceis a top-level pure function and the only code that builds a newUiState. It is the unit under test.stateisasStateFlow(): read-only, and nostateInis needed because the source is already aStateFlow.- The network result comes back as
ItemsLoadedorLoadFailed, so loading, success and failure are all visible in the reducer. A failure becomes state instead of an uncaught exception that would crash the app. ItemsLoadedis public here for brevity, so the UI could send it. Larger setups keep internal results in a separate type (MVIKotlin calls them messages).
Run the idea in plain Kotlin
The same reducer replayed over a recorded list of intents, the way you would reproduce a bug report. Folding the same intents again gives the same state.
data class UiState(
val items: List<String> = emptyList(),
val isLoading: Boolean = false,
val error: String? = null,
val selectedId: String? = null,
)
sealed interface Intent {
data object Load : Intent
data object Retry : Intent
data class Select(val id: String) : Intent
data object SelectionHandled : Intent
data class ItemsLoaded(val items: List<String>) : Intent
data class LoadFailed(val message: String) : Intent
}
fun reduce(state: UiState, intent: Intent): UiState = when (intent) {
Intent.Load, Intent.Retry -> state.copy(isLoading = true, error = null)
is Intent.ItemsLoaded -> state.copy(isLoading = false, items = intent.items)
is Intent.LoadFailed -> state.copy(isLoading = false, error = intent.message)
is Intent.Select -> state.copy(selectedId = intent.id)
Intent.SelectionHandled -> state.copy(selectedId = null)
}
fun main() {
val intents = listOf(
Intent.Load,
Intent.LoadFailed("offline"),
Intent.Retry,
Intent.ItemsLoaded(listOf("a", "b")),
Intent.Select("b"),
Intent.SelectionHandled,
)
var state = UiState()
for (intent in intents) {
state = reduce(state, intent)
println(intent.toString() + " -> " + state)
}
val replayed = intents.fold(UiState(), ::reduce)
println("Replay gives the same state: " + (replayed == state))
}Expected output:
Load -> UiState(items=[], isLoading=true, error=null, selectedId=null)
LoadFailed(message=offline) -> UiState(items=[], isLoading=false, error=offline, selectedId=null)
Retry -> UiState(items=[], isLoading=true, error=null, selectedId=null)
ItemsLoaded(items=[a, b]) -> UiState(items=[a, b], isLoading=false, error=null, selectedId=null)
Select(id=b) -> UiState(items=[a, b], isLoading=false, error=null, selectedId=b)
SelectionHandled -> UiState(items=[a, b], isLoading=false, error=null, selectedId=null)
Replay gives the same state: true
In production
UiStatehad anavigateToDetail: Booleanthat the reducer set totrueafter a successful save, and the Fragment navigated when it sawtrue.- Nothing ever set it back to
false. The ViewModel survived rotation, so the new view collected the same state, sawtrueand navigated again. - Users ended up with two detail entries on the back stack; it was missed in testing because testers rarely rotated on that screen.
- After navigating, the UI now sends
Intent.NavigationHandled, and the reducer sets the flag back tofalse. - Two reducer tests cover it:
Savedsets the flag,NavigationHandledclears it. No device or coroutine needed. - A
Channelwas considered and rejected: an event received by a collector that is cancelled before it acts (for example during rotation) is lost, and it is harder to test.
- The screen state was
combine(_state, repository.observeProducts())withonStart { repository.refresh() }, turned into aStateFlowwithstateIn(viewModelScope, SharingStarted.WhileSubscribed(0), UiState()). - On rotation the old UI stops collecting before the new one starts. With a timeout of 0 the upstream was cancelled and started again, so every rotation fired a new refresh request.
- Users saw nothing wrong because the
StateFlowkept its last value; the problem showed up as request spikes in the backend metrics.
- Changed to
WhileSubscribed(5_000). The new UI subscribes well within 5 seconds, so the upstream keeps running across a rotation. - Added a test with
runTest: collect, cancel the collector, advance virtual time by 1 second, collect again, and assert the fake API was called once. - Documented when a timeout of 0 is acceptable: only for cheap upstreams where a restart costs nothing.
Common mistakes
- Putting a one-off result in UiState and never clearing it. The ViewModel survives rotation, so the new UI collects the same state and fires the navigation or message again. Add an intent such as
NavigationHandledthat the UI sends after acting, and let the reducer clear the field. - Updating state outside the reducer. Writing
_state.update { it.copy(items = items) }directly in a coroutine means some transitions bypassreduce, so reducer tests no longer cover them. Send the result back as an intent (ItemsLoaded). - Calling side effects inside the reducer. The reducer must be pure. Calling
repo.fetch()ornavController.navigate()insidereducemakes it non-deterministic and untestable. The reducer returns the next state; the ViewModel launches the side effect after the synchronous reduce. - Exposing MutableStateFlow directly to the UI. The UI can set
.valueand bypass the reducer. ExposeasStateFlow()and keep theMutableStateFlowprivate. - Using stateIn on a MutableStateFlow. It adds a second
StateFlowand a sharing coroutine but gives nothing thatasStateFlow()does not. UsestateInfor cold sources such as a Room query. - An else branch in the reducer.
else -> statesilently ignores any intent added later. Withoutelse, the compiler forces you to handle every new intent.
Interview questions
Answer out loud first. Then reveal the answer and compare it at each depth.
“What is MVI and how does it differ from MVVM?”
“How do you handle one-off events in MVI?”
“When do you need stateIn in an MVI ViewModel, and why WhileSubscribed(5_000)?”
“How do you test a reducer?”
Quiz
What is the core structural difference between MVI and MVVM?
What does WhileSubscribed(5_000L) do in stateIn?
Why must the reducer be a pure function?
UiState has navigateToDetail = true after a save, and the UI navigates when it sees true but never reports back. What happens after a rotation?
0 of 4 answered
Mini task
Convert a flat MVVM screen to MVI (15 min)
-
Pick a screen. Open a ViewModel in your project that has 3 or more public methods and 2 or more
MutableStateFloworLiveDatafields. If you do not have one, create aSearchViewModelwith aquerystring and aresultslist. -
Define
UiState. Create adata classwith every field the UI currently reads. Add aval isLoading: Boolean = falseand aval error: String? = nullif the screen does a network call. Keep it flat for now. -
Define
Intent. Create asealed interfacewith one subtype per public method on the old ViewModel. For a search screen:OnQueryChanged(text: String),Submit,Retry. -
Write
reduce. Write a top-levelfun reduce(state: UiState, intent: Intent): UiStatewith noelsebranch. No coroutines, no I/O. Add result intentsResultsLoaded(results)andSearchFailed(message).OnQueryChangedstores the query;SubmitandRetrysetisLoading = trueand clearerror; the result intents clearisLoadingand set results or the error. -
Wire the ViewModel. Replace the old fields with one
MutableStateFlow<UiState>. Expose it withasStateFlow(). InonIntent, call_state.update { reduce(it, intent) }first, then forSubmitandRetrylaunch a coroutine that calls the repository and sendsResultsLoadedorSearchFailedback throughonIntent. -
Test the reducer. Write a JUnit test (no Android) with 4 cases:
OnQueryChangedstores the query;SubmitsetsisLoading;SearchFailedsets the error and clearsisLoading;Retryclears the error. Run the test.
Done condition: The reducer test passes with zero Android dependencies. The ViewModel has exactly one public StateFlow and one onIntent method. The old multi-field ViewModel is deleted.