Architecture · 8 min read · Intermediate
ViewModel, StateFlow & Lifecycle Safety
Survive screen rotations and expose immutable `StateFlow` UI state from Android ViewModels.
What you'll learn
- Keep mutable `_uiState` private and expose read-only `StateFlow`
- Update state atomically with `_uiState.update { ... }`
- Never hold `Activity` or `View` references inside a `ViewModel`
Overview
Survive screen rotations and expose immutable StateFlow UI state from Android ViewModels.
Code Example
class CoursesViewModel : ViewModel() {
private val _uiState = MutableStateFlow<UiState>(UiState.Loading)
val uiState: StateFlow<UiState> = _uiState.asStateFlow()
}
Key Takeaways
- Keep mutable
_uiStateprivate and expose read-onlyStateFlow - Update state atomically with
_uiState.update { ... } - Never hold
ActivityorViewreferences inside aViewModel
Quick Check
Check Your Understanding
Score: 0 / 1
1. Why does Android put screen state inside a `ViewModel` rather than directly in an `Activity`?
Study Workspace
Finished this lesson?
Your progress is saved locally in your browser, no account needed.