ViewModel & UI State
ARCHITECTURE › Components
How ViewModel holds UI state across config changes and exposes it safely.
ViewModel is one of the most-asked Jetpack topics because it sits at the heart of unidirectional data flow and lifecycle correctness. Interviewers probe whether you understand exactly what it survives (config changes) versus what it does not (process death), why it must never hold UI references, and how modern APIs like viewModelScope, SavedStateHandle, factories, and hiltViewModel fit together. Expect questions that test the boundary between ViewModel, SavedStateHandle, and rememberSaveable.
What this covers
- ViewModel survives configuration changes but is cleared on process death; SavedStateHandle covers process death
- Why a ViewModel must never reference a View, Activity, Fragment, or Context (memory leaks)
- viewModelScope and automatic coroutine cancellation in onCleared
- Exposing immutable StateFlow (asStateFlow) backed by a private MutableStateFlow
- ViewModelProvider.Factory, the viewModelFactory DSL, and CreationExtras for dependencies
- SavedStateHandle for surviving system-initiated process death, plus hiltViewModel injection
Study this topic
- ViewModel & UI State explained: the guided lesson
- 14 practice quiz questions
- 9 revision flashcards
- ViewModel & UI State interview questions and answers