Preventing UI State Loss: ViewModel vs. onSaveInstanceState in Android
Stop losing UI state on device rotation. Use Android's ViewModel to decouple data from the Activity lifecycle, ensuring complex state persists across configuration changes without manual state saving.
05 Dec 2025, 08:44 UTC

Don't rebuild UI state after configuration changes; use ViewModel.
When an Android device rotates or the system needs to reclaim memory, an Activity is destroyed and recreated. Relying solely on onSaveInstanceState() for complex UI state (like user input in a form or fetched data) is brittle and limited in size. The practical solution is decoupling state from the Activity using ViewModel.
Understanding the Android Component Lifecycle
The Activity lifecycle defines predictable states: onCreate (initial creation), onStart (visible to user), onResume (active/interacting), onPause (losing focus), onStop (not visible), and onDestroy (cleanup). Configuration changes (like rotation) trigger destruction and recreation, bypassing standard state restoration unless explicitly handled.
ViewModel: State Survival
ViewModel is designed to hold and manage UI-related data in a lifecycle-conscious way. Crucially, it survives configuration changes. The data lives as long as the scope it is tied to (e.g., the scope of the owning Activity or Fragment) exists, not just the Activity instance itself.
Concrete Example: Data Persistence Through Rotation
Consider a counter in an Activity. Without ViewModel, rotation resets the count. With it, the count persists.
- In the Activity, instantiate the
ViewModelusingViewModelProvider. - Store the counter value in a
LiveDataorStateFlowwithin theViewModel. - Observe this data in the Activity's
onCreateoronStart.
Verification: Run the Activity, increment the counter, rotate the device, and verify the counter value remains unchanged in the UI. This confirms the ViewModel instance survived the recreation.
Trade-off: Scope Management
The primary limitation is scope. A ViewModel tied to an Activity will be cleared when the Activity is permanently finished (e.g., via finish()), not just rotated. If data needs to survive process death (e.g., the user navigates away and returns later), persistence must be handled via a repository layer using a database (like Room), not just the ViewModel.
To ensure correct usage, always inject or retrieve the ViewModel via ViewModelProvider, never instantiate it directly. Check logs during rotation to confirm the Activity's onDestroy and subsequent onCreate fire, while the ViewModel's scope remains active.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.