android · 8 min read

Android MVVM that stays easy to change

MVVM separates screen rendering from screen state. On Android, a ViewModel holds state across configuration changes and delegates persistence to repositories. Compose and XML can use the same state owner, which makes UI migration less disruptive.

How the pieces connect

ScreenViewModelRepository contractData implementation

A starting folder structure

app/src/main/java/com/example/app/
  presentation/home/
    HomeScreen.kt
    HomeViewModel.kt
    HomeUiState.kt
  domain/repository/CounterRepository.kt
  data/repository/MemoryCounterRepository.kt
  di/AppContainer.kt

Expose immutable screen state

Keep MutableStateFlow private and expose StateFlow. Model what the screen needs in a data class instead of exposing several unrelated booleans. A list screen may need content, refresh status, and a recoverable error together. Do not store an Activity or View in the ViewModel.

Collect with the screen lifecycle

Compose screens can collect with collectAsStateWithLifecycle. XML fragments should launch collection with viewLifecycleOwner and repeatOnLifecycle. The view lifecycle is shorter than the fragment lifecycle; binding references must be cleared when the view is destroyed.

Inject repositories, not concrete transports

The ViewModel should receive a repository interface rather than construct Retrofit or Room. Hilt, Koin, or a small manual container can supply that interface. This supports tests that control timing and failure conditions without relying on a server.

Use cases are optional coordination points

Introduce a use case when several repositories or business rules form an operation. Avoid a class per trivial getter. MVVM alone does not enforce clean dependency direction: keep data implementation imports away from presentation if that boundary matters to your team.

Try this configuration

MVVM · Jetpack Compose · Hilt · Retrofit · StateFlow

The generator includes a working counter example with a repository contract, selected dependencies, navigation, and local setup instructions. Extend the example around your own domain before shipping.

Configure your Android project →

Continue reading

Primary references

See Android architecture recommendations and ViewModel documentation for platform guidance and lifecycle behavior.