Lesson 04 · Android with Kotlin & Compose
Android: State, Lifecycle & ViewModels
Rotation destroys the activity and everything it remembered: this lesson walks the six lifecycle callbacks and the promise each one makes, splits remember from rememberSaveable, hands screen state to a ViewModel that survives configuration changes, exposes it as a StateFlow collected with collectAsStateWithLifecycle, and ends with a checklist for where every value belongs.
Prerequisites: Android: Jetpack Compose UI
Learning objectives
By the end of this lesson, you will be able to:
- Walk the activity lifecycle - onCreate, onStart, onResume, onPause, onStop, onDestroy - and explain why a rotation destroys and recreates the activity instead of patching it
- Choose between remember and rememberSaveable by asking which events the state must survive - recomposition, configuration change, process death - and what the saved instance state Bundle can hold
- Hold screen state in a ViewModel obtained with viewModel(), and state its lifetime boundaries: created on first request, surviving configuration changes, cleared when its owner is gone for good
- Expose ViewModel state as a read-only StateFlow mutated through functions, and collect it with collectAsStateWithLifecycle from lifecycle-runtime-compose so collection stops when the UI stops
- Apply a which-storage-for-which-state checklist, keeping contexts, views and composables out of the ViewModel and anything that must outlive the app on disk