MVI in practice

Learn MVI in Android to master immutable states, sealed intents, and pure reducers, while understanding the trade-offs versus MVVM in real codebases. About 25 minutes.

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) vs WhileSubscribed(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.

AspectMVVMMVI
State shapeOne immutable UiState (Google's guidance)One immutable UiState
InputMethods on ViewModelSealed Intent
Logic locationScattered in methodsOne pure reduce()
Test surfaceCall methods, assert state (needs a test dispatcher)Call reduce(state, intent); ViewModel tested separately
CostLess boilerplateMore types, overkill for small screens
One loop: intent, reduce, state
One loop: intent, reduce, state The UI sends an intent to the ViewModel, which passes the current state and the intent to a pure reduce function; the new UiState it returns is drawn by the UI, and side effects launched by the ViewModel report back as new intents. onIntent() STATE + INTENT NEW UiState DRAWS LAUNCHES NEW INTENT UI Compose screen ViewModel holds StateFlow reduce() pure function UiState one immutable value Side effect network, database
reduce is pure: it only turns the current state and an intent into a new state. Work like network calls runs as a separate side effect.

Notes

  • MVI = one immutable UiState data class + sealed Intent + pure reduce(state, intent): UiState. The reducer has no side effects and no coroutines.
  • Expose the reducer's MutableStateFlow with asStateFlow(). Use stateIn(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 uses compareAndSet internally, so concurrent updates do not lose writes. Always prefer update over value =.
  • Sealed Intent makes every user action explicit and the when in the reducer exhaustive. When the reducer uses when as an expression without an else branch, 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 as MessageShown; 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. Sealed UiState (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, no runTest, 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.
  • stateIn with WhileSubscribed(0) stops the upstream the instant the last collector leaves, so a rotation restarts it and repeats its work. The StateFlow keeps its last value, so the UI does not flash; the cost is the repeated query or request.
  • In the ViewModel, call reduce synchronously 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
        }
    }
}
  • reduce is a top-level pure function and the only code that builds a new UiState. It is the unit under test.
  • state is asStateFlow(): read-only, and no stateIn is needed because the source is already a StateFlow.
  • The network result comes back as ItemsLoaded or LoadFailed, 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.
  • ItemsLoaded is 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

Navigation fired again after rotation
  • UiState had a navigateToDetail: Boolean that the reducer set to true after a successful save, and the Fragment navigated when it saw true.
  • Nothing ever set it back to false. The ViewModel survived rotation, so the new view collected the same state, saw true and 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.
The fix
  • After navigating, the UI now sends Intent.NavigationHandled, and the reducer sets the flag back to false.
  • Two reducer tests cover it: Saved sets the flag, NavigationHandled clears it. No device or coroutine needed.
  • A Channel was 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.
A network call on every rotation
  • The screen state was combine(_state, repository.observeProducts()) with onStart { repository.refresh() }, turned into a StateFlow with stateIn(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 StateFlow kept its last value; the problem showed up as request spikes in the backend metrics.
The fix
  • 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 NavigationHandled that 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 bypass reduce, 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() or navController.navigate() inside reduce makes 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 .value and bypass the reducer. Expose asStateFlow() and keep the MutableStateFlow private.
  • Using stateIn on a MutableStateFlow. It adds a second StateFlow and a sharing coroutine but gives nothing that asStateFlow() does not. Use stateIn for cold sources such as a Room query.
  • An else branch in the reducer. else -> state silently ignores any intent added later. Without else, 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)

  1. Pick a screen. Open a ViewModel in your project that has 3 or more public methods and 2 or more MutableStateFlow or LiveData fields. If you do not have one, create a SearchViewModel with a query string and a results list.

  2. Define UiState. Create a data class with every field the UI currently reads. Add a val isLoading: Boolean = false and a val error: String? = null if the screen does a network call. Keep it flat for now.

  3. Define Intent. Create a sealed interface with one subtype per public method on the old ViewModel. For a search screen: OnQueryChanged(text: String), Submit, Retry.

  4. Write reduce. Write a top-level fun reduce(state: UiState, intent: Intent): UiState with no else branch. No coroutines, no I/O. Add result intents ResultsLoaded(results) and SearchFailed(message). OnQueryChanged stores the query; Submit and Retry set isLoading = true and clear error; the result intents clear isLoading and set results or the error.

  5. Wire the ViewModel. Replace the old fields with one MutableStateFlow<UiState>. Expose it with asStateFlow(). In onIntent, call _state.update { reduce(it, intent) } first, then for Submit and Retry launch a coroutine that calls the repository and sends ResultsLoaded or SearchFailed back through onIntent.

  6. Test the reducer. Write a JUnit test (no Android) with 4 cases: OnQueryChanged stores the query; Submit sets isLoading; SearchFailed sets the error and clears isLoading; Retry clears 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.

Next: SavedStateHandle and process death