In what cases and why does the ViewModel get recreated when the Activity's lifecycle changes?
sobes.tech AI
Answer from AI
A ViewModel in Android is recreated when the Activity's lifecycle changes in cases where the Activity is completely destroyed and recreated, such as during a screen rotation or when there is a lack of memory.
However, if the ViewModel is used via ViewModelProvider with a connection to the Activity or Fragment lifecycle, then during a normal configuration change (e.g., rotation), the ViewModel is preserved and not recreated. It is recreated if:
- The Activity is permanently destroyed (for example, the user pressed "back").
- The application process was killed by the system, and the Activity is recreated.
The reason is that the ViewModel is tied to the lifecycle of the owner (Activity/Fragment) and lives until the owner is completely destroyed. When the Activity is recreated, a new instance of the ViewModel is created because the previous one no longer exists.
This allows for saving UI state across configuration changes but not across complete destruction and recreation of the Activity.