In Jetpack Compose, why does a checkout promo code survive rotation with `rememberSaveable` but not with `remember`, and how do you save a custom type?
answer
- the Composition dies with the activity
- saved instance state Bundle
- Bundle-storable types work out of the box
- Parcelize, listSaver, mapSaver, Saver
- inputs reset it, restoration ignores them
basics
~20 sremember lives in the Composition, which is rebuilt when the activity is recreated, so its value is lost. rememberSaveable also writes the value into saved instance state, restoring it after rotation and system-initiated process death; other types need @Parcelize or a Saver.
solid answer
~50 sA rotation destroys and recreates the activity, so the Composition and everything `remember` stored in it starts over. `rememberSaveable` behaves like `remember` across recompositions but also registers the value with the `SaveableStateRegistry`, which writes it into the activity's saved instance state `Bundle`; after rotation or system-initiated process death it is restored. Values a `Bundle` can hold work through the default `autoSaver()`. For a custom type, make it `@Parcelize` `Parcelable`, or pass a `Saver`: `listSaver`, `mapSaver` or `Saver(save, restore)`, using the `stateSaver` overload when the value sits inside `mutableStateOf`. An unsaveable value throws `IllegalArgumentException` as soon as it is registered, not at rotation. It is not restored after the user swipes the task away from Recents. Keep it small: store IDs, not the cart. Since Compose 1.9 the custom `key` parameter is deprecated and `rememberSerializable` covers `@Serializable` types.
code
kotlin · 21 linesimport androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.listSaver
import androidx.compose.runtime.saveable.rememberSaveable
data class AppliedPromo(val code: String, val discountPercent: Int)
val AppliedPromoSaver = listSaver<AppliedPromo, Any>(
save = { listOf(it.code, it.discountPercent) },
restore = { AppliedPromo(it[0] as String, it[1] as Int) },
)
@Composable
fun AppliedPromoLine() {
val promo by rememberSaveable(stateSaver = AppliedPromoSaver) {
mutableStateOf(AppliedPromo(code = "SAVE10", discountPercent = 10))
}
Text("${promo.code}: ${promo.discountPercent}% off")
}go deeper
Recall the difference: remember survives recomposition only, rememberSaveable also survives rotation and system-initiated process death through the saved instance state Bundle.
Explain the registry, what autoSaver accepts, and when to reach for @Parcelize, listSaver, mapSaver or the stateSaver overload. Know that the error fires on registration.
Judge what belongs in the Bundle: IDs and in-progress input, never large lists, and know the TransactionTooLargeException failure and the deprecated custom key since Compose 1.9.
Set a team rule for saved UI state: which element state must survive process death, a size budget for the Bundle, and when state moves to a screen-level holder or storage instead.
## Why `remember` loses the promo code `remember` stores its value in the **Composition**, the runtime's record of the UI tree. A **configuration change** such as a rotation destroys and recreates the activity by default, so `setContent` builds a brand-new Composition and every `remember` call runs its lambda again. The same happens after **system-initiated process death**, when Android kills a backgrounded app to reclaim memory and later recreates it. ## What `rememberSaveable` does `rememberSaveable` is a wrapper around `remember` that also uses the **saved instance state** mechanism: - When the value is first remembered, it is registered with the `SaveableStateRegistry` provided through the Composition. The registry key defaults to a value Compose generates from the call's position in the composition tree. - When the host saves its instance state, the registry asks each registered provider for its current value and puts it into the activity's `Bundle`. - When the activity or process is recreated, `rememberSaveable` asks the registry for the restored value first and only calls its `init` lambda if nothing was restored. It does **not** help when the user dismisses the task, for example by swiping it away from the Recents screen: saved instance state is discarded then, and losing a half-typed field is considered reasonable. ## What can be saved without extra code The default saver, `autoSaver()`, performs no conversion; the value must be something the registry can put in a `Bundle`. On Android that includes: - primitives and `String`; - `Parcelable` types, including Kotlin classes annotated with `@Parcelize`; - `Serializable` types (lambdas are rejected even though they implement it); - a `MutableState` from `mutableStateOf` whose inner value is itself saveable and whose policy is one of the three built-in ones; - since Compose 1.9, `SnapshotStateList` and `SnapshotStateSet`, which implement `Parcelable` on Android. Anything else fails fast. The registry checks the value when it is registered and throws `IllegalArgumentException` with a message such as "cannot be saved using the current SaveableStateRegistry", suggesting a custom `Saver`. A `MutableState` with a custom `SnapshotMutationPolicy` gets its own message asking for a custom `Saver`. ## Saving a custom type | Option | When to use it | |---|---| | `@Parcelize` + `Parcelable` | The class is yours and Parcelable is acceptable | | `listSaver` | Convert to a list of saveable values, read back by index | | `mapSaver` | Same, but with string keys instead of indexes | | `Saver(save, restore)` | Full control; `save` may return null to skip saving | | `rememberSerializable` | A `@Serializable` class with kotlinx.serialization (Compose 1.9+) | ```kotlin data class AppliedPromo(val code: String, val discountPercent: Int) val AppliedPromoSaver = listSaver<AppliedPromo, Any>( save = { listOf(it.code, it.discountPercent) }, restore = { AppliedPromo(it[0] as String, it[1] as Int) }, ) var promo by rememberSaveable(stateSaver = AppliedPromoSaver) { mutableStateOf(AppliedPromo(code = "", discountPercent = 0)) } ``` Use the `saver` parameter when `rememberSaveable` returns the object itself, and `stateSaver` when it returns a `MutableState` wrapping the object. When the class is your own and Parcelable is acceptable, `@Parcelize` is the shortest route; a `Saver` is the choice for a type you cannot annotate, or when you want to save only part of an object. Library state objects follow the same design: `rememberLazyListState` is built on `rememberSaveable` with a dedicated saver. ## Inputs and restoration rules 1. `rememberSaveable` takes `inputs`, the counterpart of `remember`'s `keys`: when one changes, the stored value is discarded and `init` runs again. 2. Restoration does **not** validate against the inputs that were current when the value was saved; the restored value is used as is. 3. If a `Saver`'s `save` returns null, nothing is saved and `init` runs after recreation; `listSaver` returns null for an empty list. 4. If `restore` returns null, the value is initialised again. ## What not to save, and what changed in 1.9 - The `Bundle` is limited in size and shared with everything else that writes saved state, especially in single-activity apps. Large objects or lists can end in `TransactionTooLargeException`. Save the minimum, such as the typed code or a product ID, and reload the rest from storage. - Compose 1.9 deprecated the `key` parameter of `rememberSaveable`: a custom key bypassed positional scoping and caused accidental sharing or loss of state, especially in nested lazy layouts. Remove it and let the position decide. - Compose 1.9 also added `rememberSerializable`, which saves a kotlinx.serialization `@Serializable` type without writing a `Saver`.
- When does the `IllegalArgumentException` about `SaveableStateRegistry` appear, and why there?When `rememberSaveable` first registers the value, which happens as it is remembered during composition, the registry checks that the value can be saved. An unsaveable initial value therefore fails on first display, not at the first rotation, which makes the bug easy to catch in development.
- What do `rememberSaveable`'s `inputs` do, and what do they not guarantee?They work like `remember` keys: when an input changes, the stored value is dropped and `init` runs again. They are not checked on restoration, so a value saved under old inputs comes back unchanged after recreation even if the inputs would now differ.
- Why not keep the whole cart, with product details, in `rememberSaveable`?The saved-state `Bundle` is limited and shared with every other saver in the activity; a large payload can crash with `TransactionTooLargeException`. Save the minimum needed to rebuild the screen, such as the typed promo code or item IDs, and load the rest from the data layer.
remember is holding your coat while you stay in the room; when the building is evacuated and rebuilt, the coat is gone. rememberSaveable checks the coat in at the cloakroom, which only takes items that fit its hangers, and gives you a ticket to collect it after the rebuild.
- remember keeps its value across rotation if the composable stays on screen
- rememberSaveable restores state after the user swipes the task away from Recents
- Any plain data class works in rememberSaveable without @Parcelize or a Saver
- An unsaveable initial value only fails later, when the activity saves its state
- Saving the full cart in rememberSaveable is the simplest way to survive process death
- Pass a custom key to rememberSaveable to share its value between screens
Assumes Jetpack Compose 1.12; since 1.9 rememberSaveable's custom key is deprecated, rememberSerializable exists and SnapshotStateList is Parcelable on Android.