withLocalRetainedValuesStore

Functions summary

R
@Composable
<R : Any?> withLocalRetainedValuesStore(
    store: RetainedValuesStore,
    content: @Composable () -> R
)

Installs the given store over the provided content and returns the result of the lambda.

Cmn

Functions

withLocalRetainedValuesStore

@Composable
fun <R : Any?> withLocalRetainedValuesStore(
    store: RetainedValuesStore,
    content: @Composable () -> R
): R

Installs the given store over the provided content and returns the result of the lambda. Use to install a RetainedValuesStore in all non-unit returning content lambdas. For content that returns Unit, use LocalRetainedValuesStoreProvider instead.

This method of installing a RetainedValuesStore has the same guarantees and semantics as LocalRetainedValuesStoreProvider with the addition of a return value.

import androidx.compose.runtime.Composable
import androidx.compose.runtime.retain.retain
import androidx.compose.runtime.retain.retainManagedRetainedValuesStore
import androidx.compose.runtime.retain.withLocalRetainedValuesStore

@Composable
fun Content(presenter: Presenter) {
    /* ... */
}

/**
 * Retains a Presenter to compose some [Content] with model-view-presenter patterns. The
 * Presenter is retained and passed to the content, but is wrapped separately in
 * [withLocalRetainedValuesStore] to give the presenter and content different retention
 * lifespans.
 */
@Composable
fun PresentedContent(visible: Boolean) {
    val retainedValuesStore = retainManagedRetainedValuesStore()

    if (visible) {
        val presenter =
            withLocalRetainedValuesStore(retainedValuesStore) {
                // Retain presenter for future reuse
                retain { Presenter() }
            }

        // Show content from the Presenter, but don't retain values in
        // the presenter's store
        Content(presenter)
    }
}
Parameters
store: RetainedValuesStore

The RetainedValuesStore to install as the LocalRetainedValuesStore

content: @Composable () -> R

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

Returns
R

The result of content