LocalRetainedValuesStoreProvider

Functions summary

Unit

Installs the given RetainedValuesStore over the provided content such that all values retained in the content lambda are owned by store.

Cmn

Functions

LocalRetainedValuesStoreProvider

@Composable
fun LocalRetainedValuesStoreProvider(
    store: RetainedValuesStore,
    content: @Composable () -> Unit
): Unit

Installs the given RetainedValuesStore over the provided content such that all values retained in the content lambda are owned by store. When this provider is removed from composition (and the content is therefore removed with it), the store will be notified to start retaining exited values so that it can persist all retained values at the time the content exits composition.

Note that most RetainedValuesStore implementations can only be provided in one location and composition at a time. Attempting to install the same store twice may lead to an error.

import androidx.compose.runtime.Composable
import androidx.compose.runtime.retain.LocalRetainedValuesStoreProvider
import androidx.compose.runtime.retain.RetainedEffect
import androidx.compose.runtime.retain.retain
import androidx.compose.runtime.retain.retainManagedRetainedValuesStore

@Composable
fun CollapsingMediaPlayer(visible: Boolean) {
    // Important: This retainedValuesStore is created outside of the if statement to ensure
    // that it lives as long as the CollapsingMediaPlayer composable itself.
    val retainedValuesStore = retainManagedRetainedValuesStore()

    // This content is only shown when `visible == true`
    if (visible) {
        LocalRetainedValuesStoreProvider(retainedValuesStore) {
            // Create a media player that will be retained when the CollapsingMediaPlayer is not
            // visible. This component can continue to play audio when the video is hidden.
            val mediaPlayer = retain { MediaPlayer() }
            RetainedEffect(mediaPlayer) {
                mediaPlayer.play()
                onRetire { mediaPlayer.stop() }
            }

            // Render the video component inside the RetainedContentHost.
        }
    }
}
Parameters
store: RetainedValuesStore

The RetainedValuesStore to install as the LocalRetainedValuesStore

content: @Composable () -> Unit

The Composable content that the store will be installed for. This content block is invoked immediately in-place.