When is a ViewModel Created?
Suppose you have:
class ProfileViewModel : ViewModel()
and inside your screen:
@Composable
fun ProfileScreen(
viewModel: ProfileViewModel = viewModel()
) {
}
The ViewModel is not created when the app starts.
It is created when the screen first requests it.
User opens Profile Screen
↓
viewModel() called
↓
Android checks:
"Do I already have a ProfileViewModel?"
↓
No
↓
Create ProfileViewModel
What happens during recomposition?
Suppose state changes:
Text(name)
changes from:
Manoj
to:
Manoj Sai
Compose recomposes.
Many beginners think:
Screen recomposed
↓
ViewModel recreated
❌ Wrong.
The same ViewModel instance is reused.
Screen Recompose #1
↓
Same ViewModel
Screen Recompose #2
↓
Same ViewModel
Screen Recompose #100
↓
Same ViewModel
This is why ViewModels survive recompositions.
What happens during screen rotation?
Imagine:
Portrait
↓
Rotate
↓
Landscape
Activity gets recreated.
Without ViewModel:
plaintext
Data lost
With ViewModel:
Activity destroyed
↓
New Activity created
↓
Same ViewModel reused
That's one of the biggest reasons ViewModels exist.
## When is ViewModel Destroyed?
The ViewModel lives as long as its owner lives.
For example:
plaintext
Profile Screen opened
↓
ViewModel created
↓
User stays on screen
↓
ViewModel alive
Then:
plaintext
User presses Back
↓
Profile screen removed
↓
ViewModel no longer needed
↓
onCleared()
↓
ViewModel destroyed
## What is onCleared()?
Before Android destroys the ViewModel it calls:
kotlin
override fun onCleared() {
super.onCleared()
}
Think of it as:
plaintext
"Hey ViewModel,
I'm about to destroy you.
Clean up anything you're using."
At this moment:
kotlin
viewModelScope.cancel()
is automatically triggered.
Real Example with Navigation
Suppose:
plaintext
HomeScreen
↓
ProfileScreen
User opens Profile:
ProfileScreen created
↓
ProfileViewModel created
User stays there:
plaintext
ProfileViewModel alive
User returns to Home:
plaintext
ProfileScreen removed from back stack
↓
ProfileViewModel.onCleared()
↓
ProfileViewModel destroyed
## Navigation Compose Case
Suppose:
plaintext
Home
↓
Profile
↓
Settings
plaintext
Current back stack:
Home
Profile
Settings
plaintext
When you're on Settings:
ProfileViewModel
plaintext
may still be alive because Profile is still in the navigation back stack.
Only when Profile is removed from the back stack:
Home
Settings
plaintext
then:
ProfileViewModel destroyed
Complete Lifecycle
User opens screen
↓
Android creates ViewModel
↓
ViewModelScope created
↓
Coroutines launched
↓
Screen recomposes many times
↓
Same ViewModel reused
↓
User leaves screen permanently
↓
onCleared()
↓
viewModelScope cancelled
↓
All coroutines cancelled
↓
ViewModel destroyed
This is why we say:
A ViewModel survives recompositions and configuration changes (like rotation), but it is destroyed when its owner is permanently removed and Android calls onCleared().
Top comments (0)