Skip to content

Function: watchAtom()

API / @xmachines/play-atom / watchAtom

function watchAtom<T>(atom, onValue): Cleanup;

Defined in: play-atom/src/watch-atom.ts:58

Subscribes to one atom, and coalesces the notifications into one microtask.

@xstate/store notifies an observer SYNCHRONOUSLY from set. This function keeps that notification, and it defers the callback to a microtask. One batch of synchronous writes therefore calls the callback one time, with the last value. The cleanup function is idempotent.

The lifecycle:

  • The disposed flag stops a callback after the cleanup: the microtask returns at once when the cleanup runs before the microtask fires.
  • The scheduled guard removes the duplicates of rapid synchronous writes: one batch of synchronous writes queues one microtask only.
  • The guard clears BEFORE the callback, and not after it. A callback that WRITES the atom that it watches therefore schedules the next delivery, and it reaches the caller with the value that it wrote. A callback that THROWS keeps the watch, because the throw leaves the microtask and never reaches the subscription.

The library owns the dependency edges. @xstate/store builds the subscription on an effect, and the effect holds ONE edge to the atom for the life of the watch. A caller therefore arms the watch one time, and no call site of this function counts emissions or re-arms anything.

A CAUTION for a callback that writes the atom that it watches: the write reaches the callback, so a callback that writes a NEW value on every call runs again for ever, and the microtask queue drains never. That is the loop of the caller, and this function bounds it not. A write of the SAME value ends the sequence by itself, because an atom notifies for a value that it holds already never.

The return is a Cleanup: a function, and a Disposable. A caller that keeps the release in a field and runs it from a teardown keeps that code. A caller inside one scope writes using and writes no teardown:

using stop = watchAtom(count, render);

Type Parameters

Type Parameter
T

Parameters

ParameterTypeDescription
atomReadable<T>The Atom or the ReadonlyAtom to subscribe to.
onValue(value) => voidThe function reads the current atom value after each change.

Returns

Cleanup

The release. It removes the subscription.

Example

import { createAtom, watchAtom } from "@xmachines/play-atom";
const count = createAtom(0);
const stop = watchAtom(count, (value) => console.log(value));
count.set(1);
count.set(2); // One microtask, and the callback reads 2 one time.
stop();