0
0
Android Kotlinmobile~10 mins

Why ViewModel survives configuration changes in Android Kotlin - UI Rendering Impact

Choose your learning style9 modes available
Component - Why ViewModel survives configuration changes

This UI component explains how the ViewModel in Android helps keep data alive even when the device rotates or the screen configuration changes. It shows that the ViewModel is tied to the lifecycle of the activity or fragment but is not destroyed on configuration changes, so the UI can quickly restore its state.

Widget Tree
Activity
├── ViewModelStore
│   └── ViewModel
└── UI Components (e.g., TextView, Button)
The Activity hosts a ViewModelStore which holds the ViewModel instance. UI components like TextView and Button are children of the Activity. When configuration changes happen, the Activity is recreated but the ViewModelStore and its ViewModel survive, allowing UI components to access the same data.
Render Trace - 4 Steps
Step 1: Activity
Step 2: ViewModelStore
Step 3: ViewModel
Step 4: UI Components
State Change - Re-render
Trigger:Device rotation or configuration change
Before
Activity with UI and ViewModel showing current data
After
New Activity instance created, ViewModel instance reused
Re-renders:Entire Activity UI components re-created but ViewModel data remains intact
UI Quiz - 3 Questions
Test your understanding
What happens to the ViewModel when the device rotates?
AIt survives and keeps the data
BIt is destroyed and recreated
CIt loses all data
DIt is paused but not destroyed
Key Insight
In Android, ViewModel is designed to survive configuration changes like screen rotations by being stored in a ViewModelStore tied to the Activity lifecycle. This allows the UI to quickly restore its state without losing data or needing to reload from scratch, improving user experience and app performance.