MVI Gives an Android Screen Exactly One State at a Time
This article is translated from "MVI in Android — Designing Screens That Can Only Be in One State at a Time", originally at https://medium.com/@aleyvaschz/mvi-in-android-designing-screens-that-can-only-be-in-one-state-at-a-time-1ad894b8ff3e, published by Adrian Leyva on August 12, 2026.
A practical guide to unidirectional data flow with Kotlin, coroutines, and Jetpack Compose
There is a specific bug that every Android developer eventually hits. A tester attaches a screenshot showing a loading indicator spinning above an error message, both sitting on top of a half-filled list. You can't reproduce it. You read the ViewModel three times, the logic looks fine. Two days later you find the cause: a network request returned after the user pulled to refresh; a boolean flipped in the wrong order; the screen ended up in a combination of values that nobody designed.
This bug isn't a coding error in the traditional sense; it's a design flaw. When a screen is described by five independent variables, it can have 32 different configurations, and the team only considered 4 of them. The rest have always existed, just waiting for the right race condition to trigger them.
Model-View-Intent (MVI) exists precisely to solve this problem. It isn't a brand-new library, and it doesn't replace everything you already know. It's a discipline you apply on top of the architecture you probably already use. The core idea is simple: at any moment, your screen has exactly one state; that state is produced in exactly one place; and it only changes in response to explicit, named events.
This article explains what MVI actually means in a modern Android codebase, how to implement it with Kotlin Flows and Jetpack Compose, how to test it, and when it doesn't apply.
What MVI tries to solve
Most Android teams write something close to MVVM. The ViewModel exposes a few observable properties, the UI collects them, and user actions call public methods on the ViewModel. This works fine, and for many screens the ceremony is just right.
Friction appears as screens get more complex. Consider a typical product search ViewModel written in the traditional style:
class ProductListViewModel : ViewModel() {
private val _isLoading = MutableStateFlow(false)
val isLoading: StateFlow<Boolean> = _isLoading.asStateFlow()
private val _products = MutableStateFlow<List<Product>>(emptyList())
val products: StateFlow<List<Product>> = _products.asStateFlow()
private val _error = MutableStateFlow<String?>(null)
val error: StateFlow<String?> = _error.asStateFlow()
private val _isEmpty = MutableStateFlow(false)
val isEmpty: StateFlow<Boolean> = _isEmpty.asStateFlow()
}
Here there are four independent sources of truth. Nothing in the type system prevents isLoading being true while error is non-null. Nothing forces isEmpty to stay consistent with products. Every new feature adds a flag, and every flag doubles the number of theoretical states. Eventually the UI layer compensates with defensive conditionals, and correctness depends on everyone remembering to update the right fields in the right order.
MVI collapses those four properties into one and eliminates the whole class of problems.
The three parts of the contract
An MVI screen is defined by a short contract with three parts. Writing this contract before any implementation is the most valuable habit the pattern teaches.
- State is an immutable snapshot of everything the screen needs to render. If an element isn't in state, it can't be on screen.
- Intents are user actions or lifecycle signals, expressed in the user's language rather than the implementation's.
RetryClickedis an intent;SetLoadingTrueis not. - Effects are one-time events that don't belong in state at all: navigation to another screen, showing a Snackbar, haptic feedback, and so on.
The product search screen's contract looks like this:
data class ProductListState(
val query: String = "",
val content: Content = Content.Idle,
val isRefreshing: Boolean = false
) {
sealed interface Content {
data object Idle : Content
data object Loading : Content
data class Success(val products: List<Product>) : Content
data object Empty : Content
data class Failure(val message: String) : Content
}
}
sealed interface ProductListIntent {
data class QueryChanged(val query: String) : ProductListIntent
data object SearchSubmitted : ProductListIntent
data object RetryClicked : ProductListIntent
data class ProductClicked(val productId: String) : ProductListIntent
}
sealed interface ProductListEffect {
data class NavigateToDetail(val productId: String) : ProductListEffect
data class ShowMessage(val message: String) : ProductListEffect
}
Note the role of the Content hierarchy. Loading and failure are no longer independent booleans that happen to coexist; they are mutually exclusive branches of a sealed interface, so the impossible combination that caused the original bug is now unrepresentable. The compiler enforces the design decision instead of relying on code review opinions.
The separation of state and effects is more important than it looks. State gets replayed: when the device rotates or the process resumes, the UI re-renders from the latest state, which is normal behavior. Effects should not be replayed. Nobody wants the same Snackbar to appear after every configuration change, and nobody wants to navigate twice. Modeling them as separate channels is what makes that distinction enforceable.
Distinguish user actions from system observations
In real projects, separating intents from internal events saves a lot of trouble. Intents come from outside the ViewModel. Internal events are the results of work the ViewModel initiated: repository responses, timer fires, cache emissions, and so on.
Both need to modify state, but they have different origins and different names. Separating them keeps the intent hierarchy free of entries like DataLoadedSuccessfully, which a user will never trigger and the UI layer should never call.
internal sealed interface ProductListEvent {
data class QueryUpdated(val query: String) : ProductListEvent
data object LoadStarted : ProductListEvent
data class LoadSucceeded(val products: List<Product>) : ProductListEvent
data class LoadFailed(val message: String) : ProductListEvent
data class RefreshingChanged(val isRefreshing: Boolean) : ProductListEvent
}
The reducer
MVI's reputation rests largely on the reducer. It's a pure function that takes the current state and an event and returns the next state. It does no I/O, starts no coroutines, and touches nothing outside its parameters.
internal fun ProductListState.reduce(event: ProductListEvent): ProductListState =
when (event) {
is ProductListEvent.QueryUpdated -> copy(query = event.query)
ProductListEvent.LoadStarted -> copy(
content = if (content is ProductListState.Content.Success) {
content
} else {
ProductListState.Content.Loading
}
)
is ProductListEvent.LoadSucceeded -> copy(
content = if (event.products.isEmpty()) {
ProductListState.Content.Empty
} else {
ProductListState.Content.Success(event.products)
},
isRefreshing = false
)
is ProductListEvent.LoadFailed -> copy(
content = ProductListState.Content.Failure(event.message),
isRefreshing = false
)
is ProductListEvent.RefreshingChanged -> copy(isRefreshing = event.isRefreshing)
}
Now all the rules about this screen's behavior live in one easy-to-read block. For example, the decision to keep showing existing results during a refresh instead of flashing a loading indicator is three lines in the LoadStarted branch. Before, that rule was scattered across coroutines, boolean assignments, and conditionals in layouts.
Because the reducer is pure, it's also trivially testable, which is why MVI screens tend to have unusually high test coverage without anyone forcing it.
The ViewModel
With the contract and reducer in place, the ViewModel becomes thin. Its job is to receive intents, coordinate async work, hand events to the reducer, and emit effects.
@HiltViewModel
class ProductListViewModel @Inject constructor(
private val searchProducts: SearchProductsUseCase
) : ViewModel() {
private val _state = MutableStateFlow(ProductListState())
val state: StateFlow<ProductListState> = _state.asStateFlow()
private val _effects = Channel<ProductListEffect>(Channel.BUFFERED)
val effects: Flow<ProductListEffect> = _effects.receiveAsFlow()
private var searchJob: Job? = null
fun onIntent(intent: ProductListIntent) {
when (intent) {
is ProductListIntent.QueryChanged -> {
dispatch(ProductListEvent.QueryUpdated(intent.query))
}
ProductListIntent.SearchSubmitted -> search(_state.value.query)
ProductListIntent.RetryClicked -> search(_state.value.query)
is ProductListIntent.ProductClicked -> {
sendEffect(ProductListEffect.NavigateToDetail(intent.productId))
}
}
}
private fun search(query: String) {
searchJob?.cancel()
searchJob = viewModelScope.launch {
dispatch(ProductListEvent.LoadStarted)
searchProducts(query)
.onSuccess { products ->
dispatch(ProductListEvent.LoadSucceeded(products))
}
.onFailure { throwable ->
dispatch(ProductListEvent.LoadFailed(throwable.toUserMessage()))
sendEffect(ProductListEffect.ShowMessage(throwable.toUserMessage()))
}
}
}
private fun dispatch(event: ProductListEvent) {
_state.update { current -> current.reduce(event) }
}
private fun sendEffect(effect: ProductListEffect) {
_effects.trySend(effect)
}
}
Two details deserve a pause.
The first is _state.update { }. Using the atomic update function rather than assigning to _state.value ensures that concurrent updates from different coroutines stack on top of each other instead of overwriting. In screens with multiple parallel data sources, this is the difference between being always correct and being occasionally wrong.
The second is searchJob?.cancel(). Structured concurrency handles cancellation, but only if you hold a reference. Cancelling the previous search before starting a new one prevents a slow response for query "sh" from arriving after a fast response for "shoes" and overwriting it. MVI doesn't handle out-of-order results by itself; it gives you a single place to deal with them.
Wiring up the UI
The Compose layer receives one state object and sends intents back. It contains no business decisions.
@Composable
fun ProductListRoute(
onNavigateToDetail: (String) -> Unit,
viewModel: ProductListViewModel = hiltViewModel()
) {
val state by viewModel.state.collectAsStateWithLifecycle()
val snackbarHostState = remember { SnackbarHostState() }
val lifecycleOwner = LocalLifecycleOwner.current
LaunchedEffect(viewModel, lifecycleOwner) {
viewModel.effects
.flowWithLifecycle(lifecycleOwner.lifecycle, Lifecycle.State.STARTED)
.collect { effect ->
when (effect) {
is ProductListEffect.NavigateToDetail -> {
onNavigateToDetail(effect.productId)
}
is ProductListEffect.ShowMessage -> {
snackbarHostState.showSnackbar(effect.message)
}
}
}
}
ProductListScreen(
state = state,
snackbarHostState = snackbarHostState,
onIntent = viewModel::onIntent
)
}
@Composable
private fun ProductListScreen(
state: ProductListState,
snackbarHostState: SnackbarHostState,
onIntent: (ProductListIntent) -> Unit
) {
Scaffold(
snackbarHost = { SnackbarHost(snackbarHostState) }
) { padding ->
Column(modifier = Modifier.padding(padding)) {
SearchField(
query = state.query,
onQueryChange = { onIntent(ProductListIntent.QueryChanged(it)) },
onSubmit = { onIntent(ProductListIntent.SearchSubmitted) }
)
when (val content = state.content) {
ProductListState.Content.Idle -> IdleHint()
ProductListState.Content.Loading -> FullScreenLoader()
ProductListState.Content.Empty -> EmptyResults(query = state.query)
is ProductListState.Content.Failure -> ErrorMessage(
message = content.message,
onRetry = { onIntent(ProductListIntent.RetryClicked) }
)
is ProductListState.Content.Success -> ProductGrid(
products = content.products,
onProductClick = { onIntent(ProductListIntent.ProductClicked(it)) }
)
}
}
}
}
The exhaustive when on the sealed interface is a quiet but significant advantage. Add a new content branch next quarter and the compiler will point out every screen that needs to handle it. With a string of booleans, there is no such guarantee.
Separating the route from the stateless screen also means the screen composable accepts plain parameters, which makes previews and screenshot testing straightforward.
Testing becomes mechanical
The reducer is pure, so testing behavior requires no coroutine machinery at all.
@Test
fun `keeps existing results visible while refreshing`() {
val initial = ProductListState(
query = "shoes",
content = ProductListState.Content.Success(listOf(sampleProduct))
)
val result = initial.reduce(ProductListEvent.LoadStarted)
assertThat(result.content).isEqualTo(initial.content)
}
@Test
fun `empty response maps to empty content`() {
val result = ProductListState(query = "shoes")
.reduce(ProductListEvent.LoadSucceeded(products = emptyList()))
assertThat(result.content).isEqualTo(ProductListState.Content.Empty)
}
For the ViewModel itself, you only assert the sequence of emitted states, which reads almost like a specification for the feature.
@Test
fun `failed search emits failure state and a message effect`() = runTest {
coEvery { searchProducts("shoes") } returns Result.failure(IOException())
val viewModel = ProductListViewModel(searchProducts)
viewModel.state.test {
assertThat(awaitItem().content).isEqualTo(ProductListState.Content.Idle)
viewModel.onIntent(ProductListIntent.QueryChanged("shoes"))
awaitItem()
viewModel.onIntent(ProductListIntent.SearchSubmitted)
assertThat(awaitItem().content).isEqualTo(ProductListState.Content.Loading)
assertThat(awaitItem().content).isInstanceOf(ProductListState.Content.Failure::class.java)
}
}
Important caveats
MVI has real costs, and teams that adopt it without talking about those costs tend to abandon it halfway.
- State classes can become junk drawers. It's easy to add a nullable field on complex screens to handle every edge case. Resist that urge. If a piece of data belongs to a distinct part of the screen, model it as a nested sealed type or a separate substate and reduce it independently.
- Recomposition costs can rise if you're careless. A single large state object means every change emits a new instance. Compose handles that well when state is stable and composables read only what they need, but if you pass the whole state object down five layers, you break that property. Pass each composable the minimal slice it actually needs.
- Effects can be lost. A
Channeldelivers to a single collector. If your effect flow is collected in a composable that leaves composition at the wrong time, events can be dropped. A buffered channel with lifecycle-aware collection, as shown above, covers the common case. Anything truly critical, like a completed payment, should live in state or persistent storage, not in a transient effect. - Boilerplate is real. Writing three types and a reducer for a screen that shows a static list of settings isn't worth it. Shared generic base classes or a small internal library can reduce duplication, but they don't remove the conceptual overhead.
- Not everywhere needs it. Splash screens, a static "About" page, or a simple form with two fields don't need MVI. The payoff scales with the number of async sources a screen coordinates and the number of visual states it can occupy. Use MVI for checkout flows and search results, not for terms and conditions pages.
Conclusion
MVI is less a framework and more a set of constraints you voluntarily accept. You give up the convenience of mutating a few independent fields, and in exchange you get a screen whose behavior is described by one immutable type and one pure function. Reproducing a bug becomes constructing a state object; adding a feature becomes adding a branch the compiler ensures you don't forget. Start with a screen you already worry about. Write the contract before implementing, keep the reducer pure, and let sealed types eliminate the combinations that should never have existed.
Thanks for reading!
Welcome to search and follow the WeChat official account 「稀有猿诉」 (Rare Ape Speaks) for more quality articles!
Protect originality, please do not republish!