BeCuriouzBeCuriouz

Learn something new every day

📱 Mobile Programming
🔄

Rotate your Android phone — why doesn't your data vanish?

💡 A ViewModel outlives Activity recreation like screen rotation, but not the OS killing your app's process — that still needs saved state.

Rotating an Android device seems harmless, but under the hood it's violent: the system destroys and recreates your entire Activity to load layouts sized for the new orientation. Any state held in the Activity — a half-typed form, a loaded list, a network result — is gone. This is called a configuration change, and it also fires for language switches, dark-mode toggles, and window resizing.

The fix is the ViewModel, part of Android's Jetpack libraries. A ViewModel is deliberately not tied to the Activity's lifecycle. It lives in a ViewModelStore that Android retains across the destroy-and-recreate cycle, so the same instance is handed back to the freshly rebuilt Activity. Your data survives because it was never stored in the thing that got destroyed.

The crucial nuance beginners miss: a ViewModel survives configuration changes, but it does not survive process death. If Android kills your app in the background to reclaim memory, the ViewModel — and everything in it — is wiped. When the user returns, you get a brand-new ViewModel. For state that must outlive that, you need SavedStateHandle or persistent storage. ViewModel handles rotation; it is not a durable save.

🔄 Rotate your Android phone — why doesn't your data vanish? — BeCuriouz