Unidirectional data flow

Learn unidirectional data flow in Android: events go up to the ViewModel and one immutable state comes down, which prevents common state bugs. About 25 minutes.

Why it matters

  • Predictable state makes debugging and testing straightforward: given the same event sequence, the state is always the same.
  • It eliminates the 'who changed this?' bug class when a timer, a network callback, and a user tap all write to the same ViewModel.
  • Interviewers use UDF to check whether you understand state ownership, atomic updates, and the boundary between state and side effects.
  • It is the idea behind Google's recommended app architecture, MVVM with a single StateFlow, and MVI, so most architecture interview questions build on it.

The simple explanation

  • Think of a bank account. Deposits and withdrawals are events; the balance is state.
  • You never edit the balance directly. You submit a transaction (an event).
  • The bank computes the new balance from the old balance plus the transaction (a pure reducer).
  • Two simultaneous transactions are processed one after the other, never merged (atomic update).
  • Replay every transaction from the start and you always land on the same balance (determinism).
  • A 'payment sent' notice is shown once and then dismissed; the bank records that you saw it, so it does not pop up every time you open the statement.

Unidirectional data flow (UDF) is the rule that data moves in one direction only: events travel up from the UI to the ViewModel and Repository, and state travels back down as a new immutable snapshot. The UI never mutates state; it emits events and renders whatever state it receives.

In Android the state is an immutable data class (or a sealed hierarchy) exposed as a StateFlow<UiState> from the ViewModel. The UI collects this flow and rebinds or recomposes on every emission. Events are user actions such as a tap or typed text. They enter the ViewModel through plain methods (onRefresh(), onQueryChange(text), as in the simulator below) or through a single onEvent(event) entry point; both are UDF. Results of async work (a repository call finishing) are applied inside the ViewModel, and they also become a new state.

The ViewModel holds a private MutableStateFlow and updates it with update { }, which makes the read-modify-write atomic: it uses compareAndSet and retries if another coroutine changed the value in between. This prevents lost updates when two coroutines write concurrently. Optionally, a pure reducer takes the old state and an event and returns the new state with no side effects. Side effects (network calls, navigation) are triggered separately after the reducer runs.

ChoiceWhen to use
Flat data classFew fields, no mutually exclusive states
sealed hierarchyLoading / Success / Error are the main states
stateIn(WhileSubscribed(5_000))Converting a cold Flow to a hot one shared across collectors
Field in UiState that the UI clears after actingOne-off results (show a message, move on after a save); Google's recommended way

The key invariant: given the same sequence of events, the state is always the same. This makes the system testable and debuggable. Try the simulator below to watch an event travel up and the new state travel back down.

Try it: events up, state down

Send an event from the UI and follow it. The UI never changes itself; it only draws the state.

  1. UI
  2. ViewModel
  3. Repository
What happened, in order
  1. Nothing yet. Send an event.
UiState right now
UiState(
  isLoading = false,
  query = "",
  items = [Kotlin, Compose, Coroutines, Room],
  error = null
)
Events up, state down
Events up, state down The user taps. The UI sends the event to the ViewModel through onEvent. The ViewModel asks the repository for data and gets the result, updates its state, and exposes the new UiState through a StateFlow. The UI draws the new state. User taps Refresh Draws the new state onEvent(event) LOAD DATA RESULT UPDATE STATE NEW UiState UI draws UiState ViewModel owns the state Repository loads data
The UI never changes itself: it sends an event, and redraws only when a new UiState comes back down.

Notes

  • Events go up, state goes down. The UI is a pure function of the current state; it never writes state directly.
  • MutableStateFlow.update { } is atomic (uses compareAndSet). Using value = from two coroutines can lose an update.
  • Expose StateFlow<UiState> (read-only) to the UI, never MutableStateFlow. This enforces the one-writer rule at the type level.
  • A pure reducer is a top-level fun reduce(state, event): UiState with no launch, no repository call, no println. Same input always gives the same output.
  • stateIn(SharingStarted.WhileSubscribed(5_000)) keeps a cold flow alive for 5 seconds after the last collector drops, then cancels it. Use it when converting a cold Flow to a shared hot one.
  • One-off results (a message, moving on after a save) belong in UiState as a field the UI clears by calling the ViewModel once it has acted (for example onMessageShown()). A field that is never cleared fires again after rotation. A SharedFlow with replay = 0 drops events while nobody collects; a Channel buffers them but can still lose one that is received by a collector cancelled before it acts.
  • A sealed UiState (Loading / Success / Error) makes illegal states unrepresentable. A flat data class is simpler but allows contradictory combinations (e.g., isLoading = true and error != null at the same time).
  • In MVI the reducer is the only place state changes happen. In MVVM the ViewModel can have several methods that each call update. MVI costs more boilerplate but makes every transition go through one testable function; update already prevents lost writes in both.
  • Test the reducer as a pure function with no coroutines. Test the ViewModel with runTest, a test Main dispatcher and a fake repository. Test process death by constructing the ViewModel with a SavedStateHandle that has pre-populated keys.
  • SavedStateHandle survives process death but not the user dismissing the task or force-stopping the app. It is stored in a Bundle, so keep it small: ids and queries, not lists or images.

Code example

This shows a minimal UDF screen: a sealed event hierarchy, a pure reducer, and a ViewModel that applies the reducer atomically and then fires side effects. The UI only reads state and calls onEvent.

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
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,
)
 
sealed interface UiEvent {
    data object Load : UiEvent
    data class ItemSelected(val id: String) : UiEvent
    data object Retry : UiEvent
}
 
// Pure reducer: no side effects, same input -> same output.
fun reduce(state: UiState, event: UiEvent): UiState = when (event) {
    UiEvent.Load, UiEvent.Retry -> state.copy(isLoading = true, error = null)
    is UiEvent.ItemSelected -> state.copy(selectedId = event.id)
}
 
interface Repository {
    // main-safe; catches its own errors but rethrows CancellationException
    suspend fun fetchItems(): Result<List<String>>
}
 
class ScreenViewModel(private val repo: Repository) : ViewModel() {
    private val _state = MutableStateFlow(UiState())
    val state: StateFlow<UiState> = _state.asStateFlow()  // read-only to UI
 
    fun onEvent(event: UiEvent) {
        _state.update { reduce(it, event) }  // atomic, pure
        when (event) {
            UiEvent.Load, UiEvent.Retry -> load()
            is UiEvent.ItemSelected -> Unit // state only: the UI reacts to selectedId
        }
    }
 
    private fun load() {
        viewModelScope.launch {
            val result = repo.fetchItems()
            _state.update { old ->
                result.fold(
                    onSuccess = { items ->
                        old.copy(items = items, isLoading = false, error = null)
                    },
                    onFailure = { e ->
                        old.copy(isLoading = false, error = e.message ?: "Unknown")
                    },
                )
            }
        }
    }
}
  • _state is private; only state (a read-only StateFlow from asStateFlow()) is visible outside the class, so the UI cannot write to it.
  • Every write uses update, so a user event and a finishing load() cannot overwrite each other's change.
  • The reducer is a top-level pure function. The side effect (load()) lives outside it, keeping the reducer testable without coroutines. The ViewModel does not navigate; the UI decides what to do with selectedId.

Run the idea in plain Kotlin

A pure reducer replayed over a list of events. Running the same events twice gives the same state.

data class UiState(
  val count: Int = 0,
  val label: String = "idle",
)

sealed interface Event {
  data object Increment : Event
  data object Decrement : Event
  data class SetLabel(val text: String) : Event
}

fun reducer(state: UiState, event: Event): UiState {
  return when (event) {
      Event.Increment -> state.copy(count = state.count + 1, label = "incremented")
      Event.Decrement -> state.copy(count = state.count - 1, label = "decremented")
      is Event.SetLabel -> state.copy(label = event.text)
  }
}

fun main() {
  var state = UiState()
  val events: List<Event> = listOf(
      Event.Increment,
      Event.Increment,
      Event.Decrement,
      Event.SetLabel("done"),
  )
  println("Initial: count=" + state.count + ", label=" + state.label)
  for (event in events) {
      state = reducer(state, event)
      println("After " + event + " -> count=" + state.count + ", label=" + state.label)
  }
  var check = UiState()
  for (event in events) {
      check = reducer(check, event)
  }
  println("Deterministic check (same events, same result): " + (state == check))
}

Expected output:

Initial: count=0, label=idle
After Increment -> count=1, label=incremented
After Increment -> count=2, label=incremented
After Decrement -> count=1, label=decremented
After SetLabel(text=done) -> count=1, label=done
Deterministic check (same events, same result): true

In production

Lost update in a multi-source ViewModel
  • A dashboard screen had a timer on Dispatchers.Default that updated a countdown and a network result that updated a list, both writing to the same MutableStateFlow with _state.value = _state.value.copy(...).
  • When both ran at the same moment on different threads, both read the same old value and the second write dropped the first change. Users saw the list vanish when the timer ticked, or the countdown jump back.
  • The bug was intermittent and hard to reproduce because it depended on coroutine scheduling.
The fix
  • Replaced every value = with update { old -> old.copy(...) }, which is atomic.
  • Extracted a pure reducer so all state transitions went through one function.
  • Added a concurrency test: two coroutines fire update many times each; the final state must reflect both.
Duplicate navigation after rotation
  • Navigation to a detail screen was triggered by collecting a SharedFlow with replay = 1 from the ViewModel.
  • After a configuration change, the new Fragment re-collected the flow and the last navigation event was replayed, so the app navigated again.
  • When the replay arrived while the detail screen was already showing, the NavController threw IllegalArgumentException because the navigation action does not exist from the current destination.
The fix
  • Replaced the SharedFlow with a selectedId: String? field in UiState. The UI navigates when it is non-null and then calls viewModel.onNavigated(), which sets it back to null.
  • Added a ViewModel unit test: after selecting an item selectedId is set, and after onNavigated() it is null, so a re-collection after rotation has nothing to replay.
  • A Channel was considered, but it can still lose an event received by a collector that is cancelled before it navigates, and it is harder to assert in tests.

Common mistakes

  • Mutating state in place. If UiState holds a MutableList and you call add(x) on it, then set the same object again, StateFlow compares it with equals, sees no change and does not emit. Use read-only List fields and return a new copy via copy(items = items + x).
  • Using value = instead of update { }. value = is not atomic. Two coroutines can read the same old value, compute two new values, and the second write silently overwrites the first. update uses compareAndSet and retries.
  • Putting an event in the state and never clearing it. A navigateTo: String? field that nobody resets fires again every time the UI re-collects the flow, for example after rotation. The UI must call the ViewModel (onNavigated()) after acting, and the ViewModel sets the field back to null.
  • Exposing MutableStateFlow to the UI. The UI or a composable can then call value = or emit, breaking the one-writer rule. Expose StateFlow (read-only) and keep MutableStateFlow private.
  • Calling a repository inside the reducer. The reducer must be pure. A repository call inside it makes the function impure, untestable without a fake, and introduces a race between the reducer and the async result.
  • A misleading initial value in stateIn. The non-suspending stateIn(scope, started, initialValue) shows initialValue until the upstream emits. If that value says "empty list" instead of "loading", the UI flashes an empty screen first. Pick an initial value that means loading.

Interview questions

Answer out loud first. Then reveal the answer and compare it at each depth.

“What is unidirectional data flow and why does it matter?”

“How do you handle one-off events like navigation or a toast in UDF?”

“MVVM versus MVI: when would you choose one over the other?”

“How do you test a ViewModel that uses UDF?”

Quiz

What does update { } on a MutableStateFlow guarantee?

Which way of delivering a one-off navigation result does Google's architecture guidance recommend?

What does SharingStarted.WhileSubscribed(5_000) do?

What is a key property of a pure reducer?

0 of 4 answered

Mini task

Convert a bidirectional ViewModel to UDF (15 min)

  1. Open a simple ViewModel where the UI writes state directly (a public MutableStateFlow, or several public mutable fields the Fragment sets).
  2. Make the MutableStateFlow<UiState> private, expose asStateFlow(), and add a single fun onEvent(event: UiEvent) method that the UI calls instead.
  3. Extract a top-level fun reduce(state: UiState, event: UiEvent): UiState that handles every state transition. No launch, no repository call, no println inside it.
  4. Inside onEvent, call _state.update { reduce(it, event) } first, then start side effects (such as a repository call) in a when block. Navigation stays in the UI.
  5. Write a unit test: test the reducer directly with 5 events in sequence, then test the ViewModel with runTest, a test Main dispatcher and a fake repository, asserting state.value after the events.

Done condition: the test passes, no MutableStateFlow is visible outside the ViewModel, and the reducer function body contains no launch, no repository call, and no println.

Next: MVVM in practice