Interview frequency: …
Short answer
It separates UI data and logic from the screen's lifecycle, and stays alive in memory while the Activity is recreated on device rotation, ending only when the screen is permanently closed.
Explanation
The ViewModel is created by ViewModelProvider and managed by a ViewModelStoreOwner. When a configuration change such as screen rotation occurs, the ViewModel is not destroyed but is re-attached to the new Activity instance. Its onCleared() is called only when the owner's real lifecycle ends (a call to finish() or the user leaving the back stack).
Code example
class UserViewModel : ViewModel() {
private val _users = MutableStateFlow<List<User>>(emptyList())
val users: StateFlow<List<User>> = _users.asStateFlow()
override fun onCleared() {
super.onCleared()
// Clean up active resources and subscriptions
}
}Common mistakes
- Passing a reference to the Activity, a Context, or any View object into the ViewModel, which causes a certain memory leak.
- Creating a ViewModel instance manually through UserViewModel() instead of using ViewModelProvider or a Jetpack delegate (by viewModels()).