Skip to content
Tutorials Center
My learning

Topics

Lesson 58 of 104 ยท App Architecture

UI State, Events and MVI-style Modelling

Model Android screens with one UiState (loading, content, error), send user actions as events, handle one-off effects safely and use a reducer for predictable transitions.

A screen is rarely just "a list". It is loading, then it shows a list, then the refresh fails, then it offers a retry, and a snackbar says "Saved" exactly once. If each of these facts lives in its own variable (isLoading, items, errorMessage, showSnackbar), the variables can contradict each other: loading and error at the same time, an error with stale items, a snackbar that appears again after rotation. Most "weird UI" bugs are such impossible combinations.

The cure is to model the screen's situation deliberately. This lesson shows how to describe a screen as a single UI state, how the user's actions reach the ViewModel as events, how an MVI-style reducer keeps transitions predictable and how to deal with one-off effects like snackbars and navigation. It builds on ViewModel and State Hoisting and Unidirectional Data Flow. The Compose and ViewModel code is read-only because it needs the Android SDK; the TryIt blocks are runnable stand-ins in plain Kotlin that implement the same state machines.

One state for one screen

The first rule: a screen has one UiState, produced by the ViewModel and rendered by the composable. For a screen with distinct modes, a sealed type makes impossible states impossible to write:

Kotlin
// read-only example
sealed interface ArticlesUiState {
    data object Loading : ArticlesUiState
    data class Content(val articles: List<ArticleUi>, val refreshing: Boolean = false) : ArticlesUiState
    data class Error(val message: String) : ArticlesUiState
}

@Composable
fun ArticlesScreen(state: ArticlesUiState, onRefresh: () -> Unit) {
    when (state) {
        ArticlesUiState.Loading -> LoadingIndicator()
        is ArticlesUiState.Content -> ArticleList(state.articles, state.refreshing, onRefresh)
        is ArticlesUiState.Error -> ErrorMessage(state.message, onRetry = onRefresh)
    }
}

Because when over a sealed type is exhaustive, adding a new state makes the compiler point at every place that must handle it. There is no way to have "Loading and Error" at once, because they are different classes.

The alternative is a single data class with fields:

Kotlin
// read-only example: a form screen, where everything is on at the same time
data class EditUiState(
    val title: String = "",
    val body: String = "",
    val titleError: String? = null,
    val isSaving: Boolean = false,
)

Choose by asking: can several of these facts be true together? A form has text, errors and a saving flag all at once, so a data class fits. A screen that is either loading or showing data or failed is a sealed hierarchy. Often you combine both: a sealed Loading/Content/Error where Content is a data class with its own fields.

Keep UI state ready to draw: formatted strings, booleans like canSubmit, lists already filtered. Derived values can be computed properties on the data class (val canSubmit get() = title.isNotBlank() && !isSaving), so the composable has no logic to get wrong.

Events: how actions go up

State flows down, events flow up. An event is something that happened on the screen: "the user tapped Refresh", "the query text changed". There are two common ways to send them to the ViewModel:

Kotlin
// read-only example: option 1, one function per event
class ArticlesViewModel : ViewModel() {
    fun onRefresh() { /* ... */ }
    fun onArticleClick(id: Int) { /* ... */ }
}

// option 2, a single entry point with a sealed event type (MVI style)
sealed interface ArticlesEvent {
    data object Refresh : ArticlesEvent
    data class ArticleClicked(val id: Int) : ArticlesEvent
}

fun onEvent(event: ArticlesEvent) { /* when (event) { ... } */ }

Functions per action are simple and idiomatic for Compose, and the screen receives lambdas such as onRefresh: () -> Unit. A single onEvent function is the MVI (Model-View-Intent) style: all inputs pass through one door, which makes it easy to log, replay and test them. Both are fine; be consistent within one app. Avoid passing the whole ViewModel to composables: pass state and lambdas, which keeps composables previewable and reusable.

Events are facts about the UI, not commands about the implementation. Prefer onSaveClicked to saveToDatabase: the ViewModel decides what to do about the click.

The reducer: state plus event gives new state

In the MVI style, the heart of the screen is a pure function:

TEXT
reduce(currentState, event) -> newState

It has no side effects and no hidden inputs, so you can test every transition with a plain function call. The ViewModel feeds events through it, performs the side work (loading data) and sends the results back in as new events.

stateDiagram-v2
    [*] --> Loading
    Loading --> Content: Loaded
    Loading --> Error: Failed
    Error --> Loading: Retry
    Content --> Content: Refresh (refreshing = true)
    Content --> Content: Loaded
    Content --> Content: Failed (keep the old data)

Every arrow is one reducer branch; anything not drawn is not allowed.

Here is that diagram as code. The reducer is exactly the kind of logic that you can run outside Android.

Kotlin A reducer with explicit state transitions (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Read the output against the diagram. A failed refresh while content is showing does not replace the list with an error screen; the user keeps what they had. A Retry while the content is already shown is ignored. These decisions are visible in one function, and each is a one-line test.

Loading, content and error

Almost every data screen has these three modes. Design them on purpose:

  • Loading is the initial state, before any data exists. Show a progress indicator or a skeleton.
  • Content is the success state. Keep a refreshing flag inside it for pull-to-refresh so that old data stays visible during the refresh.
  • Error replaces the screen only when there is nothing to show. If you already have content, prefer a transient message and keep the content.

An empty list is a Content state with a special rendering (an illustration and a hint), not an error. Distinguish "no results" from "failed to load", because they need different words and actions.

One-off effects: snackbars and navigation

State describes what the screen looks like. Some things are not state but happenings: show a snackbar once, navigate to the next screen, open a share sheet. If you model them as state, they stick: after a rotation the state is still there and the snackbar appears again. There are two common solutions.

Option A: model the event as state and consume it. Add a field such as userMessage: String?. The UI shows the message and then tells the ViewModel to clear it. Because the message is part of the state, it cannot be lost if the UI is not visible (it simply waits), and it is shown exactly once, as long as the UI reliably calls messageShown(). This is the approach the official guidance prefers.

Kotlin
// read-only example
data class SaveUiState(val userMessage: String? = null, val saved: Boolean = false)

@Composable
fun SaveScreen(state: SaveUiState, onMessageShown: () -> Unit, onSaved: () -> Unit) {
    val snackbarHostState = remember { SnackbarHostState() }
    state.userMessage?.let { message ->
        LaunchedEffect(message) {
            snackbarHostState.showSnackbar(message)
            onMessageShown()
        }
    }
    if (state.saved) LaunchedEffect(Unit) { onSaved() }
    // ... Scaffold with SnackbarHost(snackbarHostState)
}

Option B: a channel of effects. The ViewModel owns a Channel<Effect>(Channel.BUFFERED) exposed with receiveAsFlow(), and the UI collects it. It is concise, but it has pitfalls: an effect sent while nobody is collecting can be lost or delivered late, and collecting must be lifecycle-aware (Collecting Flows Safely). Use it for effects you can afford to miss, and prefer Option A for anything important such as navigation after a successful save.

The stand-in shows the difference. The same screen is "rendered" three times, including a simulated rotation. In the naive version the message stays in state and shows again; in the consuming version it is shown once.

Kotlin Messages as state: show once, then consume (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Without consumption the "Could not save" message re-appears after the rotation, and so does "Saved" later. With messageShown(), each message appears once.

Putting it together

A solid screen setup has this shape:

  1. The ViewModel exposes one StateFlow<UiState> (see StateFlow and collectAsStateWithLifecycle).
  2. The composable takes the state plus lambdas for events.
  3. Events reach the ViewModel, which reduces state, calls repositories and feeds results back as state.
  4. One-off happenings are modelled as consumable state.
  5. The state class is plain Kotlin, so a unit test can create it and assert on it, and a @Preview can render it with fake values.

Common mistakes

  • Several independent booleans (isLoading, isError) that can be true together. Use a sealed type or derive the booleans.
  • Replacing content with an error on a failed refresh. Keep the stale data and show a transient message.
  • Putting Context, strings from resources or Color into the state. Use ids or semantic values, and resolve them in the UI.
  • Sending navigation or toasts through state without consuming them, so they repeat on rotation.
  • Exposing mutable state to the UI. The screen reads state and calls functions.
  • Huge onEvent functions that mix reduction and I/O. Keep the reducer pure and do side work around it.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why model a loading-or-content-or-error screen as a sealed hierarchy?

    Each case is its own type, so contradictory states cannot exist, and the compiler flags every place that does not handle a new case.
  2. 2. In the reducer example, what should a Failed event do while the screen already shows content?

    Users should keep the data they already have; the failure can be reported with a transient message instead of an error screen.
  3. 3. What is the main problem with keeping a snackbar message in UI state and never clearing it?

    State outlives the composition. Without a messageShown callback that clears the field, each re-creation of the UI displays the message again.
  4. 4. What is a reducer in the MVI style?

    A reducer has no side effects, so each transition can be tested with a plain function call.

Summary

  • Give each screen one UiState: a sealed hierarchy for exclusive modes, a data class when many facts are true together.
  • Keep the state ready to draw and plain Kotlin, so it is easy to test and preview.
  • Events flow up as lambdas or a sealed Event type with one onEvent entry point (MVI style).
  • A pure reduce(state, event) function makes transitions explicit and testable.
  • Keep old content on failed refreshes; use Error only when there is nothing to show.
  • Model one-off messages as consumable state (userMessage plus messageShown); use effect channels only for effects you can afford to miss.
  • The Compose and ViewModel code is read-only; the TryIts run the reducer and message logic in plain Kotlin.

Next: StateFlow and collectAsStateWithLifecycle