0
0
Android Kotlinmobile~15 mins

Why ViewModel survives configuration changes in Android Kotlin - Why It Works This Way

Choose your learning style9 modes available
Overview - Why ViewModel survives configuration changes
What is it?
A ViewModel is a special component in Android apps that holds and manages UI-related data. It is designed to survive configuration changes like screen rotations, so the data stays intact. This means the app does not lose important information or restart processes when the device changes orientation or other settings.
Why it matters
Without ViewModel, every time the screen rotates or a configuration changes, the app would lose its current data and state, causing a poor user experience. Users would see resets, lost inputs, or delays. ViewModel solves this by keeping data alive across these changes, making apps feel smooth and reliable.
Where it fits
Before learning this, you should understand Android app components like Activities and Fragments and how configuration changes affect them. After this, you can learn about LiveData, data binding, and advanced state management techniques to build robust apps.
Mental Model
Core Idea
ViewModel acts like a safe storage box that keeps your app's data safe and ready, even when the screen flips or the device changes.
Think of it like...
Imagine you are writing a letter on a piece of paper, and suddenly the wind blows and flips the paper over. Without a clip, your paper might fly away or get lost. The ViewModel is like a clip that holds your paper firmly so it doesn't get lost when the wind (configuration change) blows.
┌───────────────┐      ┌───────────────┐
│   Activity    │      │ Configuration │
│ (UI screen)   │      │   Change      │
└──────┬────────┘      └──────┬────────┘
       │                      │
       │ recreates            │ triggers
       ▼                      ▼
┌───────────────┐      ┌───────────────┐
│   ViewModel   │◄─────┤  Retained by  │
│ (Data holder) │      │ ViewModelStore│
└───────────────┘      └───────────────┘
Build-Up - 6 Steps
1
FoundationWhat is a ViewModel in Android
🤔
Concept: Introduces the ViewModel as a component that holds UI data separately from UI controllers.
In Android, Activities and Fragments control the UI but can be destroyed and recreated during configuration changes like screen rotation. A ViewModel is a class designed to store and manage UI-related data in a lifecycle-conscious way. It keeps data even if the Activity or Fragment is recreated.
Result
You understand that ViewModel is a separate place to keep data safe from UI destruction.
Understanding that ViewModel separates data from UI components is key to managing app state effectively.
2
FoundationWhat are Configuration Changes
🤔
Concept: Explains what configuration changes are and how they affect Android components.
Configuration changes happen when device settings change, like rotating the screen, changing language, or connecting a keyboard. Android destroys and recreates Activities and Fragments to apply new settings. This means UI components lose their current state unless saved elsewhere.
Result
You know why Activities and Fragments restart and lose data on configuration changes.
Knowing that configuration changes cause UI destruction explains why data loss happens without special handling.
3
IntermediateHow ViewModel Survives Configuration Changes
🤔Before reading on: do you think ViewModel is recreated or kept when the screen rotates? Commit to your answer.
Concept: Shows that ViewModel instances are retained and reused across configuration changes.
When an Activity or Fragment is recreated due to a configuration change, the system keeps the existing ViewModel instance in a special store called ViewModelStore. The new UI controller gets the same ViewModel instance, so data stays intact without reloading or resetting.
Result
You see that ViewModel is not destroyed and recreated like Activities, preserving data.
Understanding ViewModelStore retention is crucial to grasp why ViewModel survives UI recreation.
4
IntermediateRole of ViewModelStore and Lifecycle
🤔Before reading on: does ViewModel survive all lifecycle events or only configuration changes? Commit to your answer.
Concept: Explains the ViewModelStore and how lifecycle affects ViewModel lifespan.
ViewModelStore is a container that holds ViewModels tied to a lifecycle owner like an Activity. It keeps ViewModels alive during configuration changes but clears them when the lifecycle owner is permanently destroyed (like when the user leaves the screen). This ensures data is kept only as long as needed.
Result
You understand that ViewModel survives configuration changes but not permanent destruction.
Knowing the lifecycle boundaries of ViewModel helps avoid memory leaks and stale data.
5
AdvancedViewModel and Memory Management
🤔Before reading on: do you think ViewModel can cause memory leaks if misused? Commit to your answer.
Concept: Discusses how ViewModel manages memory and what to avoid.
ViewModel holds references to data but should not hold references to UI views or contexts to prevent memory leaks. It is designed to be lifecycle-aware and cleared automatically when no longer needed. Developers must avoid storing UI elements inside ViewModel.
Result
You learn best practices to keep apps efficient and leak-free.
Understanding memory management in ViewModel prevents common bugs and app crashes.
6
ExpertInternal Mechanism of ViewModel Retention
🤔Before reading on: do you think ViewModelStore uses static variables or another method to retain ViewModels? Commit to your answer.
Concept: Reveals the internal Android framework mechanism that retains ViewModels across configuration changes.
Android uses a non-configuration instance mechanism inside Activity and Fragment to save ViewModelStore. When configuration changes happen, the system calls onRetainNonConfigurationInstance to keep ViewModelStore alive. The new Activity instance retrieves this store, so ViewModels survive. This is a clever use of Android's lifecycle callbacks.
Result
You gain deep insight into how Android preserves ViewModels behind the scenes.
Knowing the internal retention mechanism explains why ViewModel is reliable and how to troubleshoot issues.
Under the Hood
ViewModel instances are stored in a ViewModelStore tied to the lifecycle owner. When a configuration change occurs, Android calls onRetainNonConfigurationInstance to save this store. The new Activity or Fragment instance retrieves the same ViewModelStore, so the ViewModel objects are reused instead of recreated. This avoids data loss and expensive reloads.
Why designed this way?
Android needed a way to keep UI data alive without forcing developers to manually save and restore state. Using ViewModelStore and lifecycle callbacks leverages existing Android lifecycle mechanisms, making it efficient and less error-prone. Alternatives like static variables or singletons risk memory leaks and poor lifecycle awareness.
┌───────────────────────────────┐
│       Activity Instance        │
│ ┌───────────────┐             │
│ │ ViewModelStore│◄────────────┤
│ └───────────────┘             │
│          │                    │
│  onRetainNonConfigurationInstance
│          │                    │
│ ┌───────────────┐             │
│ │ Configuration │             │
│ │   Change      │             │
│ └───────────────┘             │
│          │                    │
│  New Activity Instance        │
│ ┌───────────────┐             │
│ │ ViewModelStore│────────────►│
│ └───────────────┘             │
└───────────────────────────────┘
Myth Busters - 3 Common Misconceptions
Quick: Does ViewModel survive when the user completely closes the app? Commit yes or no.
Common Belief:ViewModel keeps data alive even if the app is closed or killed by the system.
Tap to reveal reality
Reality:ViewModel only survives configuration changes while the app process is alive. If the app is closed or killed, ViewModel data is lost.
Why it matters:Assuming ViewModel keeps data forever can cause bugs where data disappears unexpectedly after app closure.
Quick: Is it safe to store UI views inside ViewModel? Commit yes or no.
Common Belief:You can store references to UI elements like buttons or text fields inside ViewModel for easy access.
Tap to reveal reality
Reality:Storing UI views in ViewModel causes memory leaks because ViewModel outlives the UI components during configuration changes.
Why it matters:Memory leaks degrade app performance and can cause crashes, making the app unreliable.
Quick: Does ViewModel automatically save data to disk during configuration changes? Commit yes or no.
Common Belief:ViewModel automatically saves and restores data to persistent storage during configuration changes.
Tap to reveal reality
Reality:ViewModel only keeps data in memory; it does not save data to disk. Developers must handle persistence separately.
Why it matters:Relying on ViewModel for persistence can cause data loss if the app is killed or crashes.
Expert Zone
1
ViewModelStore is tied to the lifecycle owner and cleared only when the owner is permanently destroyed, not on every lifecycle event.
2
Using SavedStateHandle with ViewModel allows combining in-memory survival with saved state persistence for better resilience.
3
ViewModel instances are scoped to the lifecycle owner, so sharing ViewModels between Activities requires special patterns like shared ViewModel in navigation components.
When NOT to use
ViewModel should not be used for data that must survive app process death or for very large data sets. For those cases, use persistent storage like Room database or SharedPreferences. Also, avoid using ViewModel for UI elements or context references to prevent leaks.
Production Patterns
In real apps, ViewModels often work with LiveData or StateFlow to expose data reactively to the UI. Developers combine ViewModel with repositories for clean architecture. ViewModels are scoped per screen or navigation graph to manage data lifecycle precisely.
Connections
State Management in React
Both manage UI state separately from UI components to survive re-renders or lifecycle changes.
Understanding ViewModel helps grasp how React's state hooks keep data across component updates, showing a common pattern in UI frameworks.
Cache Systems in Web Browsers
Both store data temporarily to avoid expensive reloads and improve user experience.
Knowing ViewModel's role is like browser cache clarifies why keeping data in memory speeds up apps and reduces network or computation costs.
Human Memory and Attention
ViewModel acts like short-term memory that holds important info while attention (UI) shifts or resets.
This connection shows how cognitive science concepts of memory retention relate to app data management, deepening understanding of why ViewModel matters.
Common Pitfalls
#1Storing UI views inside ViewModel causing memory leaks.
Wrong approach:class MyViewModel : ViewModel() { var button: Button? = null // wrong }
Correct approach:class MyViewModel : ViewModel() { var data: String? = null // store data only }
Root cause:Confusing ViewModel as a place for UI elements instead of data storage.
#2Expecting ViewModel to survive app process death.
Wrong approach:fun loadData() { val data = viewModel.data // assumes data always present }
Correct approach:fun loadData() { val data = viewModel.data ?: loadFromDatabase() // fallback }
Root cause:Misunderstanding ViewModel lifecycle limits and persistence needs.
#3Creating new ViewModel instance manually instead of using ViewModelProvider.
Wrong approach:val vm = MyViewModel() // wrong, bypasses lifecycle
Correct approach:val vm = ViewModelProvider(this).get(MyViewModel::class.java) // correct
Root cause:Not using Android's lifecycle-aware ViewModel creation leads to loss of retention benefits.
Key Takeaways
ViewModel holds UI data separately from Activities and Fragments to survive configuration changes like screen rotations.
Android retains ViewModel instances in a ViewModelStore that lives across configuration changes but clears when the lifecycle owner is destroyed.
ViewModel should only store data, not UI elements or contexts, to avoid memory leaks.
ViewModel does not persist data across app process death; use persistent storage for long-term data.
Understanding ViewModel's lifecycle and retention mechanism helps build smooth, reliable Android apps.