Modern Android Architecture: ViewModel, Flow, Hilt & Room
Google's recommended app architecture with ViewModels, coroutines and Flow, dependency injection with Hilt, and Room for local data.
Intermediate · about 12 hours · difficulty 4/5
Learn first: Jetpack Compose in Depth, App-wide State Tools
Google publishes a recommended architecture that most modern Android teams follow. Learning it makes any production codebase readable to you.
Layers
- UI layer: composables plus a
ViewModelthat exposes a singleStateFlow<UiState>and accepts events. - Domain layer (optional): use cases for reusable business logic.
- Data layer: repositories combining remote sources (Retrofit or Ktor) and local sources (Room), exposing
Flows.
Coroutines and Flow
viewModelScope.launchfor work tied to the screen; it cancels when the ViewModel is cleared.Flowfor streams;stateInturns a flow into state for the UI; collect in Compose withcollectAsStateWithLifecycle().- Use
withContext(Dispatchers.IO)for blocking I/O inside repositories.
Dependency injection
Hilt provides repositories and data sources to ViewModels (@HiltViewModel, @Inject constructor), and lets tests swap in fakes.
Room
Define @Entity classes, @Dao interfaces with queries returning Flow, and migrations when the schema changes.
Pitfalls
Exposing MutableStateFlow publicly lets the UI mutate state; expose read-only StateFlow.
Good enough to move on: a feature reads from Room, refreshes from the network, and the UI updates automatically through Flow.
Key concepts
- UI, domain and data layers
- ViewModel and UiState
- Coroutines and viewModelScope
- Flow and StateFlow
- Hilt dependency injection
- Room entities, DAOs and migrations
- Retrofit or Ktor client
- Multi-module projects
Mini project
Build a GitHub repo browser that caches results in Room, refreshes from the API, and exposes a single UiState from a Hilt-injected ViewModel.
Check yourself
Why should a ViewModel expose StateFlow rather than MutableStateFlow?
Free resources
- Guide to app architecture (Android Developers)
- Save data with Room (Android Developers)
- Dependency injection with Hilt (Android Developers)