Unidirectional data flow
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.
| Choice | When to use |
|---|---|
Flat data class | Few fields, no mutually exclusive states |
sealed hierarchy | Loading / 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 acting | One-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.
Send an event from the UI and follow it. The UI never changes itself; it only draws the state.
- UI
- ViewModel
- Repository
- Nothing yet. Send an event.
UiState(
isLoading = false,
query = "",
items = [Kotlin, Compose, Coroutines, Room],
error = null
)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 (usescompareAndSet). Usingvalue =from two coroutines can lose an update.- Expose
StateFlow<UiState>(read-only) to the UI, neverMutableStateFlow. This enforces the one-writer rule at the type level. - A pure reducer is a top-level
fun reduce(state, event): UiStatewith nolaunch, no repository call, noprintln. 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 coldFlowto a shared hot one.- One-off results (a message, moving on after a save) belong in
UiStateas a field the UI clears by calling the ViewModel once it has acted (for exampleonMessageShown()). A field that is never cleared fires again after rotation. ASharedFlowwithreplay = 0drops events while nobody collects; aChannelbuffers them but can still lose one that is received by a collector cancelled before it acts. - A
sealedUiState(Loading / Success / Error) makes illegal states unrepresentable. A flatdata classis simpler but allows contradictory combinations (e.g.,isLoading = trueanderror != nullat 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;updatealready 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 aSavedStateHandlethat has pre-populated keys. SavedStateHandlesurvives 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")
},
)
}
}
}
}_stateisprivate; onlystate(a read-onlyStateFlowfromasStateFlow()) is visible outside the class, so the UI cannot write to it.- Every write uses
update, so a user event and a finishingload()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 withselectedId.
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
- A dashboard screen had a timer on
Dispatchers.Defaultthat updated a countdown and a network result that updated a list, both writing to the sameMutableStateFlowwith_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.
- Replaced every
value =withupdate { 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
updatemany times each; the final state must reflect both.
- Navigation to a detail screen was triggered by collecting a
SharedFlowwithreplay = 1from 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
IllegalArgumentExceptionbecause the navigation action does not exist from the current destination.
- Replaced the
SharedFlowwith aselectedId: String?field inUiState. The UI navigates when it is non-null and then callsviewModel.onNavigated(), which sets it back tonull. - Added a ViewModel unit test: after selecting an item
selectedIdis set, and afteronNavigated()it isnull, so a re-collection after rotation has nothing to replay. - A
Channelwas 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
UiStateholds aMutableListand you calladd(x)on it, then set the same object again,StateFlowcompares it withequals, sees no change and does not emit. Use read-onlyListfields and return a new copy viacopy(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.updateusescompareAndSetand 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 tonull. - Exposing MutableStateFlow to the UI. The UI or a composable can then call
value =oremit, breaking the one-writer rule. ExposeStateFlow(read-only) and keepMutableStateFlowprivate. - 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)showsinitialValueuntil 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)
- Open a simple ViewModel where the UI writes state directly (a public
MutableStateFlow, or several public mutable fields the Fragment sets). - Make the
MutableStateFlow<UiState>private, exposeasStateFlow(), and add a singlefun onEvent(event: UiEvent)method that the UI calls instead. - Extract a top-level
fun reduce(state: UiState, event: UiEvent): UiStatethat handles every state transition. Nolaunch, no repository call, noprintlninside it. - Inside
onEvent, call_state.update { reduce(it, event) }first, then start side effects (such as a repository call) in awhenblock. Navigation stays in the UI. - 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, assertingstate.valueafter 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.