State Changes — Surviving Rotation
A user types "Monstera del" into Sprout's add-plant screen, turns the phone sideways, and the text is gone. Nothing crashed. The activity simply died and was reborn, and the half-typed name died with it. This lesson is about why, and where state must live to survive.
The rule
Rotation rebuilds the activity; keep state outside it.
A configuration change is any change to the device setup that can affect how the UI looks: rotation, switching to dark mode, changing the language, resizing a window. By default the system reacts by destroying the activity and creating a new one, so resources for the new setup get loaded.
Anything stored only in the activity object is lost. Three safer homes exist:
ViewModel— an object kept alive across configuration changes. Perfect for loaded data, such as Sprout's plant list. It is not kept if the system kills the app's process in the background.- Saved instance state — a small
Bundlethe system stores for you, and gives back even after process death. For small UI values: typed text, a selected tab, a scroll position. In Compose,rememberSaveableuses it for you. - Persistent storage — a database or file, for data that must outlive everything.
var draftName by rememberSaveable { mutableStateOf("") } // survives rotationA plain remember survives recomposition but not a configuration change.
The shortcut
For any value, ask "what should it survive?" and pick the smallest home that does.
The typed name
Small UI input, should survive rotation and process death →
rememberSaveable.
Drills
Answer fast — trust the rule.
What does Android do to an activity by default when the device rotates?
Which of these is a configuration change?
Where should Sprout keep a plant list loaded from the database so rotation does not reload it?
A value must survive both rotation and the system killing the app in the background. Which is the lightest fit for a short typed text?
Remember
- Rotation rebuilds the activity; keep state outside it.
- ViewModel survives configuration changes; saved state also survives process death.
rememberis not enough across rotation: userememberSaveablefor small UI state.
