RevenueCat Paywalls are designed in the dashboard and rendered on Android by the RevenueCat Android SDK with Jetpack Compose, and a paywall can play a different video in light and dark mode. We received a bug report against version 10.21.0 of the SDK: with such a paywall on screen, switching the system between light and dark mode changed the screen for a moment, and then the previous theme's video came back and kept playing. The renderer held the video's URI in rememberSaveable(videoUrls.url) { ... }, with the URL passed as an input, so the value should have been recomputed when the URL changed. The URL did change. So why did rememberSaveable hand back the old value?

In this article, you'll start from that report and trace inward: the two fixes it took, how rememberSaveable restores a value when an Activity is recreated, why the inputs never reach the saved state, the regression test that reproduces it, and the options for state that has to survive a restore and still follow its input. Every behavior shown was checked with tests or on an emulator.

The fundamental problem: An input that changes while nothing is composed

Before the fix, the video component resolved its URI like this:

@Composable
private fun rememberVideoContentState(
    videoUrls: VideoUrls,
    repository: FileRepository,
): URI {
    val videoUrl = rememberSaveable(videoUrls.url) {
        resolveVideoUrl(videoUrls, repository)
    }

    // Cache both resolutions in parallel in the background
    LaunchedEffect(videoUrls.url) {
        // ...
    }

    return videoUrl
}

resolveVideoUrl is a synchronous lookup: it returns the cached high resolution file if there is one, then a cached low resolution file, and the remote URL otherwise. The videoUrls argument comes from the component's state, which picks the dark variant when isSystemInDarkTheme() is true and the light one otherwise. So in dark mode the input is the dark URL, and in light mode it's the light URL.

The SDK's own PaywallActivity declares no configChanges, so switching to dark mode, which is a uiMode configuration change, destroys the Activity and creates a new one. The old composition is gone before the input changes, and the new composition starts with the dark URL already in place. The input never changes inside a composition. It changes between two of them.

That distinction didn't exist in the mental model I had written down before. In an earlier article, "Runtime Saveable: How Compose Preserves State Across Process Death", I described the inputs this way:

This mirrors how remember(key1, key2) { ... } reinitializes when keys change.

That's true within one composition. It isn't true across a restore, and the bug sits in that gap. If you've passed something derived from the theme, the locale, or the window size to rememberSaveable, you've written the same shape. A standalone app reproduces it: an input derived from the theme, and a value computed from it with rememberSaveable and with remember. campaign is a saved String that the "Change input in place" button toggles, so across a recreation only the theme part of asset changes. resolve takes a label for logcat and the input, and appends a counter shared by every row, so a new number means a new computation:

val dark = isSystemInDarkTheme()
val asset = "${campaign}_${if (dark) "dark" else "light"}.mp4"

val saveable = rememberSaveable(asset) { resolve("rememberSaveable(input)", asset) }
val remembered = remember(asset) { resolve("remember(input)", asset) }

The app declares no configChanges either, and it runs on Compose 1.11.4, the version the RevenueCat SDK compiles against today. The SDK's 10.21.x releases compiled against Compose 1.7.0, which has the same restore logic. Toggling dark mode on the emulator with adb shell cmd uimode night yes gives this:

The rows label asset as input. Ignore the retain row for now. After the Activity is recreated in dark mode, remember(input) ran again (#9) and resolved the dark asset. rememberSaveable(input), marked STALE, still returns the light asset from the very first computation (#1), and logcat shows no new computation for it.

Two bugs, one symptom: The view and the value

The report was the second round of this bug. The first fix, #4159 in 10.21.0, addressed the video view. It's an AndroidView whose factory applied the URI only when the view was created, so a composition that survived the theme change kept playing the old URI in the old view. The fix applies a changed URI in the update block:

update = { view ->
    videoView.value = view
    view.setOnReadyCallback(onReady)
    // update runs on every recomposition and setVideoURI re-prepares the player, so
    // applying it unconditionally would restart playback constantly.
    if (appliedUri.value != videoUri) {
        appliedUri.value = videoUri
        view.setVideoURI(videoUri.toUri())
    }
},

That covers the case where the composition survives, for example in an app that handles uiMode itself. The new report came from 10.21.0, which already had #4159, and from the common case where the Activity is recreated. There, a fresh view received a stale URI, because the value itself was stale. The brief change on screen that the report described turned out to be the paywall's fallback image, not the dark video. Fixing the value took a second change, #4219, which you'll see after the mechanism.

Inside rememberSaveable: Restored with the current inputs

When an Activity saves its instance state, a SaveableStateRegistry collects every saveable value into the Bundle, each under a key derived from its call site's position in the composition. A Saver converts each value into something the Bundle can hold (save) and back (restore). When the new Activity composes, each call site asks the registry for its value with consumeRestored. The rememberSaveable overloads all forward to one implementation. Looking at its core in runtime-saveable 1.11.4:

val registry = LocalSaveableStateRegistry.current

val holder = remember {
    // value is restored using the registry or created via [init] lambda
    val restored = registry?.consumeRestored(finalKey)?.let { saver.restore(it) }
    val finalValue = restored ?: init()
    SaveableHolder(saver, registry, finalKey, finalValue, inputs)
}

val value = holder.getValueIfInputsDidntChange(inputs) ?: init()
SideEffect { holder.update(saver, registry, finalKey, value, inputs) }

return value

finalKey is that position key. The holder is created once per call site inside a remember with no keys, and the inputs check is a plain array comparison:

fun getValueIfInputsDidntChange(inputs: Array<out Any?>): T? {
    return if (inputs.contentEquals(this.inputs)) {
        value
    } else {
        null
    }
}

Now trace the two ways an input can change.

When the input changes within one composition:

  1. The holder already exists, created during an earlier composition with the old inputs.
  2. getValueIfInputsDidntChange(newInputs) compares the new inputs with the old ones, finds a difference, and returns null.
  3. init() runs, and the SideEffect stores the new value and the new inputs in the holder.

When the Activity is recreated with a different input:

  1. The new composition reaches the call site for the first time, so the remember block runs.
  2. consumeRestored(finalKey) finds the value saved by the old Activity under the same finalKey, and saver.restore turns it back into the light URI.
  3. The holder is created with that restored value and the current inputs, which already hold the dark URL.
  4. getValueIfInputsDidntChange compares the dark URL with the dark URL, finds no difference, and returns the light URI.

The key observation: on a restore, the inputs are compared, but with themselves. Nothing older is available to compare against, because the inputs are never saved. The holder registers this provider with the registry:

private val valueProvider = {
    with(saver) { save(requireNotNull(value) { "Value should be initialized" }) }
}

Only value goes through the Saver. inputs is a plain field of the holder, and it's gone with the old composition. The saved entry records where the value was computed, through finalKey, but not what it was computed from. The KDoc of the inputs parameter has said so since runtime-saveable 1.8.0: "Note that state restoration DOES NOT validate against inputs provided before value was saved."

The code is byte for byte the same in 1.11.4 and in 1.13.0, the latest stable release at the time of writing, so this is current behavior rather than a version quirk.

You might expect a call site that joins the composition later to miss the saved value. In the SDK, the video's call site only joins once the component becomes visible, a frame or more after the first composition. It still gets the stale value, because consumeRestored hands out the saved entry whenever the call site first asks for it, not only on the first frame. The demo app's tests check this case explicitly.

The fix the SDK shipped: Nothing worth saving

#4219, released in 10.21.1, changed one line of logic, and made the function internal for its new test:

-    val videoUrl = rememberSaveable(videoUrls.url) {
+    val videoUrl = remember(videoUrls) {
         resolveVideoUrl(videoUrls, repository)
     }

The reasoning in the PR is short: the lookup is a synchronous cache check, so nothing is lost by not persisting it. The key also became the whole videoUrls, which compares by value, because resolveVideoUrl reads more than the main URL. remember saves nothing. A recreated Activity starts a new composition, the remember block runs, and it resolves the URL that matches the current theme. A value that's cheap to compute from its input has no reason to be saved at all.

The PR also added a regression test. It uses StateRestorationTester, which waits for the composition to go idle, saves its state, disposes the content, and composes it again from the saved state, the way an Activity recreation does:

val restorationTester = StateRestorationTester(composeTestRule)
// Not a snapshot state on purpose: the restored composition must start with the dark URLs, the way a
// recreated Activity does, instead of recomposing the live one.
var videoUrls = videoUrls(lightUrl)
var resolvedUri: URI? = null

restorationTester.setContent {
    resolvedUri = rememberVideoContentState(videoUrls, repository)
}
composeTestRule.runOnIdle { assertThat(resolvedUri).isEqualTo(lightUri) }

videoUrls = videoUrls(darkUrl)
restorationTester.emulateSavedInstanceStateRestore()

composeTestRule.runOnIdle { assertThat(resolvedUri).isEqualTo(darkUri) }

The comment is the important part. If videoUrls were a mutableStateOf, the tester's wait for idle would recompose the live composition with the dark URLs before the save. That takes the first path above, where the inputs check works, so the dark value is what gets saved, and the test would pass with the bug still in place. The demo app has a test that does this with rememberSaveable(input), and it passes against the buggy code. A plain var keeps the live composition untouched, so the restored composition is the first one to see the dark URLs, exactly as in a recreated Activity.

The SDK didn't need it, but for a derived value that's expensive to compute, retain(input) { ... } from runtime-retain sits between remember and rememberSaveable. It keeps values in memory across configuration changes, scoped to the call site, and compares its keys when a value comes back. In the demo, the retained value followed the theme in both directions, kept its counter across a recreation with the same input, and was computed again after the process was killed, because nothing it holds is saved.

When the state must survive: Tying it to its input

remember fixed the video because the URI can be computed again. Some state can't. A playback position, a scroll offset, or a choice the user made for one specific input has to survive recreation and process death, and it should still reset when the input changes. The demo app's lower section, "State that must reset when the input changes", holds a position for the current asset with five different approaches. Each row was advanced to 10 s in light mode, then the system switched to dark mode and back:

The first row is the bug again: rememberSaveable(input) carries the light asset's 10 s into the dark asset. The second row, remember(input), resets correctly on the change, but it resets on every recreation. A separate run with the "Recreate, same input" button showed it dropping to 0 s with the input unchanged, while every saveable row kept 10 s. The remaining three tie the saved state to its input.

Save the input with the value

If the inputs aren't saved, you can save them yourself. A Saver stores the input next to the value and refuses a restore when the input doesn't match:

fun <T> inputCheckingStateSaver(input: Any): Saver<MutableState<T>, Any> =
    listSaver(
        save = { state -> listOf(input, state.value) },
        restore = { saved -> if (saved[0] == input) mutableStateOf(saved[1] as T) else null },
    )

@Composable
fun <T> rememberSaveableStateFor(input: Any, init: () -> T): MutableState<T> {
    val saver = remember(input) { inputCheckingStateSaver<T>(input) }
    return rememberSaveable(input, saver = saver) { mutableStateOf(init()) }
}

A restore that returns null makes rememberSaveable fall through to init(), through restored ?: init() in the holder code above. In dark mode the saved input is the light asset, the restore is refused, and the position starts at 0. Switching back to light then finds a value saved for the dark asset, so it starts at 0 again. The value survives a recreation with the same input, and after the demo's process was killed and restored, it still came back at 10 s. Three constraints apply:

  • The input must be saveable: listSaver checks every item, so the input has to be a type the Bundle accepts.
  • The input needs value equality: saved[0] == input uses the input's equals, and after process death the restored input is a new object, so a type that compares by identity won't match. A String, a data class of such values, or an enum, which comes back as the same constant, does.
  • Wrap the whole MutableState: the Saver above saves the MutableState and goes in the saver parameter. A value Saver passed as stateSaver can't refuse a restore, because rememberSaveable wraps it in mutableStateSaver, which turns your null into mutableStateOf(null), so init() never runs. In the demo's test with a non null type, the restore then crashed with a NullPointerException when the holder checked that the restored value could be saved again.

Put the input in the key

key() takes a different route:

val position = key(asset) { rememberSaveable { mutableStateOf(0) } }

key() mixes its argument's hashCode() into the position key, so each input gets its own finalKey and its own saved slot. In dark mode, the dark key has nothing saved, so init() runs and the position starts at 0.

Now look at the third panel. Back in light mode, the light position is 10 s again. The light entry was saved by the first Activity and never consumed by the dark one, and the registry copies unconsumed restored entries into the next save, so it survived the dark Activity. Whether that's what you want depends on the state. For a per video position it may be exactly right. The input also has to produce the same hashCode() after a restore, including in a new process. That holds for a String or an Int, and for an enum on its own, because Compose mixes in its ordinal instead, but it isn't guaranteed for a type whose hashCode() depends on identity, including a data class that holds an enum.

One saved scope per input

SaveableStateHolder.SaveableStateProvider(key = input) gives each input its own registry, keyed by the input itself rather than a hash. It behaves like the key approach here, including the 10 s that comes back in light mode, and it keeps each input's state until you call removeState. The key has to be a saveable type, and providing the same key twice at once throws.

RevenueCat's tabs component has used this pattern since #4481 (11.1.0), so each tab keeps its own carousel page. Trimmed to the state handling:

val tabContentStateHolder = rememberSaveableStateHolder()
// ...
AnimatedContent(targetState = selectedTabIndex, /* ... */) { tabIndex ->
    val tab = tabsState.tabs[tabIndex]
    // Keyed by index: tab ids aren't guaranteed unique.
    tabContentStateHolder.SaveableStateProvider(key = tabIndex) {
        StackComponentView(style = tab.stack, /* ... */)
    }
}

The tabs cross fade, so two tabs are composed at once during the transition, which is why each needs a distinct key.

Choosing between them

Ask what the state is. If you can compute it again from the input, as with the video URI, use remember(input) and save nothing. If it's user state that belongs to one input and should reset when the input changes, save the input with it. If it should come back when the user returns to an earlier input, give each input its own slot with key or a SaveableStateProvider. rememberSaveable(input) alone is only safe when the input can't change between the save and the restore, and anything derived from the configuration, such as the theme, the locale, or the window size, can.

Conclusion

When you pass inputs to rememberSaveable, read them as "reset when these change while this composition is alive". A recreation isn't a change from rememberSaveable's point of view, because the new composition has no previous inputs to compare against. So before saving a value derived from an input, check whether that input can differ after a restore. If it comes from the configuration, it can, and the fix is either to stop saving the value or to tie the saved value to its input.

The fix for the stale video was one line, remember instead of rememberSaveable. It was obvious only once it was clear what the saved state holds for a call site: the value, under its position key, and no record of the inputs it was computed from.