MVVM & Unidirectional Data Flow Flashcards
ARCHITECTURE › Patterns
- What is UI state in the MVVM/UI-layer sense?
- An immutable snapshot of all the data the UI needs to render a screen. If the UI is what the user sees, UI state is what the app says they should see.
- Explain unidirectional data flow (UDF).
- State flows in one direction, down from the ViewModel to the View, while events flow up from the View to the ViewModel. The ViewModel processes events, updates state, and the new state flows back down.
- Why should a ViewModel hold no references to Views, Context, or Android framework classes?
- It outlives Views across configuration changes (so a View reference would leak), and staying framework-free keeps it unit-testable on the JVM without Robolectric or a device.
- Why model screen state as a single immutable data class instead of several mutable fields?
- A single immutable object is the single source of truth: it guarantees a consistent snapshot, prevents partial or contradictory updates, eases debugging, and lets you derive computed properties from it.
- How do you typically expose UI state from a ViewModel and consume it?
- Expose it as a read-only StateFlow (private MutableStateFlow backed) or Compose State, then collect it lifecycle-aware in the UI with collectAsStateWithLifecycle().
- How do you represent loading, error, and empty states?
- Encode them inside the immutable UI state, e.g. an isLoading flag, a userMessages/error field, and an empty list, or model the whole state as a sealed interface of Loading/Success/Error so the UI renders exactly one case.
- What does 'state down, events up' mean concretely for a Composable?
- The Composable receives state as parameters (down) and exposes event lambdas like onClick (up). It never owns or mutates business state; it hoists it to the ViewModel.
- What is the difference between business logic and UI logic, and where does each live?
- Business logic implements product requirements (bookmarking, auth) and lives in the data/domain layers. UI logic decides how to display state (formatting, navigation, snackbars) and lives in the UI/ViewModel.
- Who is allowed to mutate UI state and why?
- Only the owner or source of the data, the ViewModel, should update the state it exposes. Letting the View mutate it would create multiple sources of truth and inconsistencies.