Android Developer interview question
How do ViewModels work with the Android lifecycle?
A ViewModel retains screen state across configuration changes and is cleared when its owner finishes; it should expose UI state and launch work in viewModelScope without holding Activity or View references.
Direct answer
What a strong answer covers
How it works
A ViewModel is scoped to a ViewModelStoreOwner such as an Activity, Fragment, or navigation graph entry. When the system recreates the Activity for a rotation or a locale change, the store survives and the same ViewModel instance is returned, so loaded data and in-progress work are not lost. When the owner is finished for good, onCleared runs and viewModelScope is cancelled. The ViewModel exposes UI state as StateFlow or LiveData and receives events; it must not reference Views, Activities, or Contexts that die on recreation. Process death is a separate case handled with SavedStateHandle.
Example
A search screen keeps its query, results, and loading flag in a StateFlow inside the ViewModel, so rotating the phone re-renders the same state instantly instead of refetching. The query string is also written to SavedStateHandle so that if the OS kills the process in the background the screen restores the query, while the results are refetched.
Common mistakes
- Passing an Activity context into the ViewModel and leaking the Activity across rotations.
- Treating the ViewModel as protection against process death and losing state when the app is killed in the background.
- Observing a Flow in the ViewModel with collect that never stops, instead of exposing it to the UI with stateIn.
A useful answer structure
Answer from your own work.
Do not memorise a script: use only examples you can explain honestly in follow-up questions.
Open the desktop workspace and rehearse a clear answer in your own words.