Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
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.

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.

The shortcut

For any value, ask "what should it survive?" and pick the smallest home that does.

Deciding homes on Sprout's add screenStep 1 of 4
  1. The typed name

    Small UI input, should survive rotation and process death → rememberSaveable.

Drills

Answer fast — trust the rule.

quick drill

What does Android do to an activity by default when the device rotates?

quick drill

Which of these is a configuration change?

quick drill

Where should Sprout keep a plant list loaded from the database so rotation does not reload it?

quick drill

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.
  • remember is not enough across rotation: use rememberSaveable for small UI state.

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainThe vanishing plant name

A user types half a plant name into Sprout's add screen, rotates the phone, and the text disappears. Explain why, and say where you would keep the typed text and the loaded plant list so each survives the right events.