Skip to the workspace
Pebellslearn by building
Activities and Their Lifecycle  ›  Lesson

State Changes — Surviving Rotation

State Changes 15 minConfiguration changes such as rotation destroy and recreate an activity, so state must live in a ViewModel or saved instance state to survive.

android / State Changes — Surviving Rotation

Explore each scene at your own pace.

01 · The rule

The rule

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 Bundle the 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, rememberSaveable uses it for you.
  • Persistent storage — a database or file, for data that must outlive everything.
var draftName by rememberSaveable { mutableStateOf("") }  // survives rotation

A plain remember survives recomposition but not a configuration change.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.