Android Architecture: MVVM with ViewModel and StateFlow

Structure Android apps with MVVM—ViewModel, UI state, and unidirectional data flow.

MVVM keeps UI and logic separate and testable. Here’s how to implement it on Android with ViewModel and StateFlow.

MVVM and Android architecture
MVVM and Android architecture

Layers

  • View (Activity/Fragment/Compose) — Observes state and sends events. No business logic; only UI and user input.
  • ViewModel — Holds UI state and handles user actions. Exposes state as StateFlow or LiveData; calls repositories or use cases. Survives configuration changes.
  • Repository — Single source of truth for data. Combines local (Room) and remote (API). ViewModels depend on repositories, not data sources directly.
  • Model — Data classes and entities. Domain models and DTOs as needed.

Data flow: User → View → ViewModel → Repository → API/DB. State flows back: Repository → ViewModel → View.

Architecture adoption (Android):

Architecture pattern used

State in ViewModel

Use a single data class UiState (loading, success, error) and expose it as StateFlow<UiState>. Update in a single place (e.g. a function that loads data and sets state). Collect in the UI with collectAsState() (Compose) or repeatOnLifecycle (Views).

MVVM with ViewModel:

Takeaway

MVVM with ViewModel and StateFlow (or LiveData) is the recommended pattern. Keep ViewModels thin; put logic in repositories and use cases. Test ViewModels with unit tests and fake repositories.