rememberRetained

fun <T : Any> rememberRetained(vararg inputs: Any?, key: String? = null, init: () -> T): T(source)

Remember the value produced by init.

It behaves similarly to remember, but the stored value will survive configuration changes, such as a screen rotation.

You can use it with a value stored inside androidx.compose.runtime.mutableStateOf.

This differs from rememberSaveable by not being tied to Android bundles or parcelable. You should take care to ensure that the state computed by init does not capture anything that is not safe to persist across reconfiguration, such as Navigators. The same caveats of rememberSaveable also still apply (i.e. do not retain Android Contexts, Views, etc).

However, it does not participate in saved instance state either, so care should be taken to choose the right retention mechanism for your use case. Consider the below two examples.

The first case will retain state across configuration changes but will not survive process death.

@Composable
override fun present(): CounterState {
var state by rememberRetained { mutableStateOf(CounterState(0)) }

return CounterState(count) { event ->
when (event) {
is CounterEvent.Increment -> state = state.copy(count = state.count + 1)
is CounterEvent.Decrement -> state = state.copy(count = state.count - 1)
}
}
}

This second case will retain count across configuration changes and survive process death. However, it only works with primitives or Parcelable state types.

@Composable
override fun present(): CounterState {
var count by rememberSaveable { mutableStateOf(0) }

return CounterState(count) { event ->
when (event) {
is CounterEvent.Increment -> state = count++
is CounterEvent.Decrement -> state = count--
}
}
}

Parameters

inputs

A set of inputs such that, when any of them have changed, will cause the state to reset and init to be rerun

key

An optional key to be used as a key for the saved value. If not provided we use the automatically generated by the Compose runtime which is unique for the every exact code location in the composition tree

init

A factory function to create the initial value of this state