android-kotlin
/

Android ViewModel – Persistent UI State Management

Last Sync: Today

On this page

5
0%
5 min read
Remaining
5 minleft

Click any section to jump — progress syncs automatically

android-kotlin

Android ViewModel – Persistent UI State Management

The Role of the ViewModel

In the Android Architecture Components, the ViewModel's primary job is to store and manage UI-related data. Its unique power lies in its Lifecycle Awareness: it remains in memory during an Activity's destruction and recreation (e.g., rotation) and only clears itself when the Activity is actually finished. For an Engineering Manager, this is the key to 'Separation of Concerns'—keeping the Activity focused on rendering while the ViewModel handles the data logic.

  1. ViewModel vs. Activity State

When an Activity is recreated, its local variables are wiped. To prevent Revochamp from restarting an AI generation process every time the user tilts their phone, we shift the 'Generation Status' into the ViewModel. In 2026, we utilize Kotlin Coroutines inside the viewModelScope to ensure that background tasks are automatically canceled if the user leaves the app entirely.

KOTLINRead-only
1
class RevoViewModel : ViewModel() {
    private val _uiState = MutableStateFlow<UiState>(UiState.Idle)
    val uiState: StateFlow<UiState> = _uiState.asStateFlow()

    fun generateWidget(prompt: String) {
        viewModelScope.launch {
            _uiState.value = UiState.Loading
            val result = aiRepository.generate(prompt)
            _uiState.value = UiState.Success(result)
        }
    }
}

  1. ViewModel with SavedStateHandle

While ViewModels survive rotation, they do not survive Process Death (when the OS kills the app in the background to save RAM). To handle this, we use SavedStateHandle. This is a key-value map that persists through process death, allowing the user to return to their work in Chennai's humid outdoor conditions even if their mid-range device cleared the app from memory.

  1. The Shared ViewModel Pattern

Fragments within the same Activity can share a single ViewModel. This is a common pattern for 'Master-Detail' views in Revochamp, where one fragment updates a value and another fragment observes that change instantly, without the need for complex interface callbacks.

State Management Comparison

FeatureAndroid ViewModelFlutter Riverpod (Notifier)
PersistenceSurvives RotationSurvives Widget Rebuilds
Lifecycle AwareYes (Cleared on Finish)Manual (ref.onDispose)
ScopeActivity/Fragment ScopeGlobal or Widget Scope
ConcurrencyviewModelScope (Coroutines)Async/Await
Process DeathSavedStateHandleHydrated Bloc / Manual Save
UI BindingLiveData / StateFlowref.watch() / Consumer

Test Your Knowledge

Q1
of 3

What happens to a ViewModel when the screen is rotated?

A
It is destroyed and recreated
B
It remains in memory and is re-attached to the new Activity
C
It is paused and then resumed
D
It throws a ConfigurationException
Q2
of 3

Which component is used to persist ViewModel data specifically through system-initiated process death?

A
LiveData
B
SavedStateHandle
C
SharedPreferences
D
Intent Extras
Q3
of 3

Why should you NOT store a reference to an Activity inside a ViewModel?

A
It is too much data for the ViewModel
B
It will cause a memory leak when the Activity is destroyed
C
Activities are not serializable
D
The compiler will prevent it automatically

Frequently Asked Questions

Can I pass a Context into a ViewModel?

Never pass an Activity or View context into a ViewModel. This will cause a memory leak because the ViewModel outlives the Activity. If you need an application-level context, use 'AndroidViewModel', which provides a reference to the Application context safely.

How do I instantiate a ViewModel?

You should never call the constructor directly (e.g., 'val vm = MyViewModel()'). Instead, use 'ViewModelProvider' or the 'by viewModels()' Kotlin delegate. This allows the system to check if a ViewModel instance already exists before creating a new one.

When is onCleared() called?

'onCleared()' is called right before the ViewModel is destroyed. This is the perfect place to manually close sockets, cancel observers, or release heavy resources that aren't tied to the viewModelScope.

Previous

android navigation

Next

android livedata

Related Content

Need help?

Explore our comprehensive docs or start a chat with our tech experts.