Skip to content
Guest
Kotlin & Android · Course Syllabus Show lessons
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 _uiState private and expose read-only StateFlow
  • Update state atomically with _uiState.update { ... }
  • Never hold Activity or View references inside a ViewModel

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.

Search courses, lessons, and references

Type to search across all courses, lessons, and quick references.

Press Esc to close Powered by Pagefind