Contents
CWCoding With DhrumilCW Practical Flutter and Kotlin tutorials for working mobile developers

Home › Articles

Configuration Changes in Kotlin: Keep State Without Leaks

By Dhrumil Patel · Published · 5 min read

Smartphone being rotated between portrait and landscape orientation on a desk.
Smartphone being rotated between portrait and landscape orientation on a desk. · Foto: Pexels / Pixabay

Rotate a phone and, out of the box, an Activity is torn down and rebuilt. That surprises many developers the first time a form clears itself or a scroll position jumps. The fix is not a single API but a decision tree: what kind of state is it, how long must it live, and what should survive the user leaving the screen entirely?

This article walks through the two failure modes you will hit most often, rotation and process death, then matches each to a concrete Kotlin pattern: ViewModel for transient UI state, SavedStateHandle for small values that must survive the system killing your process, and on-disk persistence for anything that belongs to the user long term.

What Actually Happens on Rotation

On a configuration change the system destroys the current Activity instance and creates a new one, because resources such as layout direction, screen size and locale may have changed. The old instance goes through onPause, onStop and onDestroy, and a fresh instance runs onCreate again. Any plain field you held in the Activity is gone with the old instance.

The Activity's window is rebuilt from the current configuration, so a landscape layout file can be a completely different XML tree. That is the intended design: instead of mutating a live view hierarchy, you inflate the right one. The cost is that you must hand state across the boundary yourself, or let a component that outlives the Activity hold it for you.

Since Android 8.0 the default manifest behaviour is `android:configChanges` unset, meaning the platform handles rotation by recreation. Adding `configChanges="orientation|screenSize"` to avoid recreation is legal but shifts the burden onto you: you must re-resolve resources manually, and it does nothing for process death.

  • Activity instance is destroyed and recreated on rotation
  • Plain fields and anonymous listeners do not survive
  • `configChanges` avoids recreation but not process death
  • ViewModels survive rotation because they outlive the Activity
38Activity fields27View state22ViewModel only13SavedStateHandle
Rough share of rotation bugs by state location (% of cases)

ViewModel: State That Outlives Rotation but Not the Process

A ViewModel is scoped to the Activity or Fragment and is retained across configuration changes. Put your in-progress form fields, loaded lists and coroutine jobs there and rotation becomes a non-event. Retrieve it with `by viewModels()` in an Activity or `by viewModels()` from the fragment-ktx artifact in a Fragment.

The critical detail is that a ViewModel is cleared when the owner finishes for real, for example when the user presses back or the task is removed. It is not a cache. Do not put large bitmaps or a full database result set in it without a size limit; a few megabytes of retained data per screen is already generous for a phone.

Launch work with `viewModelScope`. Coroutines tied to that scope cancel automatically when the ViewModel clears, which removes a whole class of leak where a request completes after the screen is gone and tries to touch a dead view. Collect your flows with `repeatOnLifecycle` so collection pauses when the UI is not visible.

  • Use `by viewModels()` for scoping
  • Keep retained data small
  • Use `viewModelScope` for requests
  • Collect flows with `repeatOnLifecycle`

SavedStateHandle: Surviving Process Death

Process death is the scenario developers forget to test. Your app sits in the background, the system reclaims memory, and when the user returns the Activity is recreated with its saved instance state but no ViewModel. Anything held only in the ViewModel is lost, and the user sees a blank screen where their half-finished form used to be.

SavedStateHandle closes that gap. Inject it into the ViewModel constructor and it writes into the same Bundle the system preserves. Values must be Bundle-compatible: primitives, strings, Parcelable and Serializable. That means an ID, a query string, a page number, a draft text field. It does not mean a list of a thousand objects.

A Bundle survives process death but it still travels through inter-process communication, so there is a hard practical ceiling around a megabyte before `TransactionTooLargeException` territory. Treat it as a few kilobytes of important scalars. For restoring a text field, combine `SavedStateHandle` with `rememberSaveable` in Compose or an `EditText` state restore in views.

  • Bundle-compatible types only
  • Keep total size in the low kilobytes
  • Great for IDs, filters and draft text
  • Pair with `rememberSaveable` in Compose

Choosing the Right Store for Each Value

A useful rule: ask what should happen if the user leaves the screen and comes back tomorrow. If the answer is nothing should remain, the value belongs in local composable or view state. If it should survive rotation and a short trip to the background, put it in the ViewModel. If it must survive the process being killed while the user is in the middle of a task, mirror the small essentials into `SavedStateHandle`.

If the value is the user's data, such as a saved draft, a favourite or a completed order, it belongs in a database or DataStore and should be read back on start. Configuration handling is not a persistence strategy; it is a continuity strategy for one session.

Mixing these levels is the usual source of bugs. A common failure is storing a `LiveData` result only in the database layer and showing an empty state for the two hundred milliseconds before the query returns. Seed the UI from `SavedStateHandle` or the ViewModel so the first frame already has content.

  • Composable or view state: ephemeral
  • ViewModel: rotation and short backgrounding
  • SavedStateHandle: process death survival
  • Database or DataStore: real persistence

Patterns That Keep the Code Readable

Expose one immutable UI state object from the ViewModel, built with a data class, and render it in a single place. That way rotation restores everything from one source rather than six scattered observables, and the screen has exactly one truth to reason about. StateFlow with an initial value gives you a correct first frame with no empty flash.

Handle one-off events, such as a snackbar or navigation, through a `Channel` consumed as a flow, not through a value in the state object. A retained event in state will fire again after rotation, which produces the classic double snackbar. Keeping events out of state also keeps your state class serialisable and easy to test.

For fragments, remember that the fragment view lifecycle is shorter than the fragment itself. Register view-bound observers in `onViewCreated` and remove them in `onDestroyView`, or use `viewLifecycleOwner`. If you are still juggling fragment transactions by hand, it is worth comparing approaches in Jetpack Navigation vs manual fragment transactions before adding more state to the mix.

  • One immutable state class per screen
  • StateFlow with a sensible initial value
  • Channel for one-off events
  • Bind to `viewLifecycleOwner` in fragments
Where each kind of state should live
State typeSurvives rotationSurvives process deathTypical sizeBest home
Text field draftNo by defaultNoBytes to a few KBSavedStateHandle or rememberSaveable
Loaded list of itemsNo by defaultNoTens of KB to MBViewModel, re-fetch on restore
Selected tab or filterNo by defaultNoBytesSavedStateHandle
Scroll positionNo by defaultNoBytesrememberSaveable or view state
User's saved draftYes if persistedYes if persistedUnboundedRoom or DataStore
Auth tokenYes if persistedYes if persistedUnder 4 KBEncrypted storage

Testing Rotation and Process Death

Rotation is easy to test manually: enable the device's auto-rotate, or trigger it from the emulator toolbar, and watch whether the screen keeps its content. Better, write an instrumentation test with `ActivityScenario` and call `recreate()` to force the cycle deterministically in CI. That catches state that only exists in a field.

Process death is harder. Enable "Don't keep activities" in developer options to destroy every Activity as soon as it is backgrounded, then navigate away and back. The stronger tool is the emulator's ability to kill the app process while keeping the task, which exercises the real saved-instance-state restore path. If the screen comes back empty, you have found a state that belongs in `SavedStateHandle`.

If your screen is a long scrolling list, also confirm the scroll position restores. That is a separate concern from data restoration and is covered in Scrolling Widgets Compared: ListView, GridView and CustomScrollView.

  • `ActivityScenario.recreate()` in tests
  • Enable "Don't keep activities"
  • Kill the process from the emulator
  • Check scroll position separately from data
  • Rotation recreates the Activity; ViewModel is the first line of defence.
  • ViewModel does not survive process death, SavedStateHandle does.
  • Keep saved state to a few kilobytes of Bundle-compatible values.
  • Test with `recreate()` and with "Don't keep activities" enabled.
Dhrumil Patel · Editor and Flutter contributor
Writes practical Flutter tutorials focused on widgets, layout and animation. Enjoys breaking large UI problems into small, testable pieces and explaining them clearly to beginners.

Related articles

↑