Function

asContextElement

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

snapshotAsContextElementSample

@Suppress("unused")
@Sampled
fun snapshotAsContextElementSample() {
    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()
        }
    }
}
Jetpack Compose beyond MaterialFree components, screens and templates for apps that don’t look like Google’s. Copy them into your app, or let your coding agent add them.Browse for free

Content updated: