{% setvar book_path %}/reference/androidx/_book.yaml{% endsetvar %} {% include "_shared/_reference-head-tags.html" %}

SnapshotContextElementKt

public final class SnapshotContextElementKt


Summary

Public methods

static final @NonNull SnapshotContextElement

Return a SnapshotContextElement that will enter this Snapshot whenever the associated coroutine is resumed and leave this snapshot when it suspends.

Public methods

asContextElement

@ExperimentalComposeApi
public static final @NonNull SnapshotContextElement asContextElement(@NonNull Snapshot receiver)

Return a SnapshotContextElement that will enter this Snapshot whenever the associated coroutine is resumed and leave this snapshot when it suspends. The snapshot still must be disposed separately when it will no longer be used.

import androidx.compose.runtime.snapshots.Snapshot
import androidx.compose.runtime.snapshots.asContextElement

runBlocking {
    val snapshot = Snapshot.takeSnapshot()
    try {
        withContext(snapshot.asContextElement()) {
            // Data observed by separately reading stateA and stateB are consistent with
            // the snapshot context element across suspensions
            doSomethingSuspending(someObject.stateA)
            doSomethingSuspending(someObject.stateB)
        }
    } finally {
        // Snapshot must be disposed after it will not be used again
        snapshot.dispose()
    }
}