---
title: "asContextElement"
description: "Return a [SnapshotContextElement] that will [enter][Snapshot.enter] this [Snapshot] whenever the
associated coroutine is resumed and leave this snapshot when it suspends. The snapshot still must
be [disposed][Snapshot.dispose] separately when it will no longer be used."
type: "function"
---

<div class='type'>Function</div>


<a id='references'></a>
<div class='sourceset sourceset-common'>Common</div>


```kotlin
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
```kotlin
@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()
        }
    }
}
```

