asContextElement
Function
Common
public fun Snapshot.asContextElement(): SnapshotContextElement
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.
Code Examples
snapshotAsContextElementSample
@Suppress("unused")
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()
}
}
}