Lifecycles
Example
Source.onObserved runs a hook on an observable’s first observer and its
cleanup after the last. The chat’s socket opens on the first observer of
$socket and closes after the last
(Live data).
import { Source } from "@frondruntime/sorus";
// Opens the socket, and reopens it after each drop: 0.5 s after the first,
// doubling up to 30 s, back to 0.5 s once an event arrives. Returns what
// closes it. The state lives in this call, so a socket from an earlier
// observation never schedules a reconnect.
const connect = () => {
let socket: WebSocket | undefined;
let timer: ReturnType<typeof setTimeout> | undefined;
let attempt = 0;
const open = () => {
setConnection("connecting");
const next = new WebSocket(chatUrl);
next.onopen = () => {
setConnection("open");
};
next.onmessage = (event: MessageEvent) => {
attempt = 0;
receive(event.data);
};
next.onclose = () => {
setConnection("closed");
timer = setTimeout(open, Math.min(30_000, 500 * 2 ** attempt));
attempt++;
};
socket = next;
};
open();
return () => {
clearTimeout(timer);
if (socket !== undefined) {
socket.onclose = null;
socket.close();
}
// $canSend reads $connection without observing the feed: it must not
// stay "open" once the socket is closed.
setConnection("closed");
};
};
Source.onObserved($socket, connect);Source.observe holds a value observed with nothing rendered.
import { Source } from "@frondruntime/sorus";
// Keeps the profile across rooms, as a store that loads once in its
// constructor does: until the release runs, $profile stays observed and
// keeps its answer.
const holdProfile = () => Source.observe($profile);Rules
- An observer holds what it read until its stop function, release, unmount, or scope ends.
Realm.untrackedand an update read without observing, so they start no hook. - A hook starts once the call that observed has linked, and syncs outside state there: nothing reports changes made while unobserved.
Realm.disposeruns each begun hook’s cleanup once, even while the value is observed, and no later observer starts a hook.- Make a realm a component owns in the effect that disposes it: React may discard a render without cleanup. Under StrictMode the first realm is disposed and the second kept.
Answers
| Call | Answers |
|---|---|
Source.onObserved($x, () => cleanup) |
The function that removes the hook. The hook returns the cleanup. |
Source.observe($x) |
A release. Until it runs, $x’s hooks stay started and a computed value stays cached. |
With Effect
Source.observeScoped releases when its scope closes: see Programs.
See also
- Realms:
Realm.disposeand what a disposed realm answers. - Reacting: watches and autoruns.
- Boxes and computed: atoms and
write.changed. - Async state:
Computed.fromPromise.