retainManagedRetainedValuesStore

Functions summary

Functions

retainManagedRetainedValuesStore

@Composable
fun retainManagedRetainedValuesStore(): ManagedRetainedValuesStore

Retains a ManagedRetainedValuesStore. The returned store follows the lifespan defined by retain. When the retained scope is retired, it will be disposed.

Optionally, you can enable and disable retention of exited values on this scope via ManagedRetainedValuesStore.enableRetainingExitedValues and ManagedRetainedValuesStore.disableRetainingExitedValues. (The scope is enabled by default.)

import androidx.compose.animation.AnimatedContent
import androidx.compose.runtime.Composable
import androidx.compose.runtime.retain.LocalRetainedValuesStoreProvider
import androidx.compose.runtime.retain.retain
import androidx.compose.runtime.retain.retainManagedRetainedValuesStore

@Composable
fun RetainedAnimatedContent(active: Boolean, content: @Composable () -> Unit) {
    // Create a RetainedValuesStore. It will be added as a child to the current store and start
    // retaining exited values when the parent does. On Android, this store will implicitly
    // survive and forward retention events caused by configuration changes.
    val retainedValuesStore = retainManagedRetainedValuesStore()
    AnimatedContent(active) { targetState ->
        if (targetState) {
            // Install the RetainedValuesStore over the child content
            LocalRetainedValuesStoreProvider(retainedValuesStore) {
                // Values retained here will be kept when this content is faded out,
                // and restored when the content is added back to the composition.
                content()
            }
        }
    }
}