Android 12 Developer Preview is here! Try it out, and give us your feedback!

SnapshotStateObserver

class SnapshotStateObserver
kotlin.Any
   ↳ androidx.compose.runtime.snapshots.SnapshotStateObserver

Summary

Public constructors
<init>(onChangedExecutor: (callback: () -> Unit) -> Unit)

Public methods
Unit
clear(scope: Any)

Clears all model read observations for a given scope.

Unit

Remove all observations.

Unit
clearIf(predicate: (scope: Any) -> Boolean)

Remove observations using predicate to identify scope scopes to be removed.

Unit
notifyChanges(changes: Set<Any>, snapshot: Snapshot)

This method is only used for testing.

Unit
observeReads(scope: T, onValueChangedForScope: (T) -> Unit, block: () -> Unit)

Executes block, observing state object reads during its execution.

Unit

Starts watching for state commits.

Unit

Stops watching for state commits.

Unit
withNoObservations(block: () -> Unit)

Stops observing state object reads while executing block.

Public constructors

<init>

SnapshotStateObserver(onChangedExecutor: (callback: () -> Unit) -> Unit)

Public methods

clear

fun clear(scope: Any): Unit

Clears all model read observations for a given scope. This clears values for all onCommit methods passed in observeReads.

clear

fun clear(): Unit

Remove all observations.

clearIf

fun clearIf(predicate: (scope: Any) -> Boolean): Unit

Remove observations using predicate to identify scope scopes to be removed. This is used when a scope is no longer in the hierarchy and should not receive any callbacks.

notifyChanges

@TestOnly fun notifyChanges(
    changes: Set<Any>,
    snapshot: Snapshot
): Unit

This method is only used for testing. It notifies that changes have been made on snapshot.

observeReads

fun <T : Any> observeReads(
    scope: T,
    onValueChangedForScope: (T) -> Unit,
    block: () -> Unit
): Unit

Executes block, observing state object reads during its execution.

The scope and onValueChangedForScope are associated with any values that are read so that when those values change, onValueChangedForScope can be called with the scope parameter.

Observation for scope will be paused when a new observeReads call is made or when withNoObservations is called.

Any previous observation with the given scope and onValueChangedForScope will be cleared when the onValueChangedForScope is called for scope. The onValueChangedForScope should trigger a new observeReads call to resubscribe to changes. They may also be cleared using clearIf or clear.