Class

SnapshotStateObserver

Helper class to efficiently observe snapshot state reads.

Common
public class SnapshotStateObserver(private val onChangedExecutor: (callback: () -> Unit) -> Unit)

Helper class to efficiently observe snapshot state reads. See observeReads for more details.

NOTE: This class is not thread-safe, so implementations should not reuse observer between different threads to avoid race conditions.

Functions

observeReads

public fun <T : Any> observeReads(
        scope: T,
        onValueChangedForScope: (T) -> Unit,
        block: () -> 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 will be called with the scope parameter.

Observation can be paused with Snapshot.withoutReadObservation.

Parameters

scope value associated with the observed scope.
onValueChangedForScope is called with the scope when value read within block has been changed. For repeated observations, it is more performant to pass the same instance of the callback, as observedScopeMaps grows with each new callback instance.
block to observe reads within.

withNoObservations

public fun withNoObservations(block: () -> Unit)

Stops observing state object reads while executing block. State object reads may be restarted by calling observeReads inside block.


clear

public fun clear(scope: Any)

Clears all state read observations for a given scope. This clears values for all onValueChangedForScope callbacks passed in observeReads.


clearIf

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

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


start

public fun start()

Starts watching for state commits.


stop

public fun stop()

Stops watching for state commits.


notifyChanges

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

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


clear

public fun clear()

Remove all observations.