Live data
Example
The chat’s messages arrive over a WebSocket: a history when it opens, then one event per message sent or deleted. The socket is open while something observes the feed, and reconnects after a drop.
import { Atom, Computed, Realm } from "@frondruntime/sorus";
import { $messages } from "./messages.ts";
import { app } from "./realm.ts";
import { $connection } from "./state.ts";
const chatUrl = "wss://example.com/chat";
// Stands for the socket: observing a value below that reads it opens it.
const $socket = Atom.make(app);
// The socket's state, read through the atom.
const $status = Computed.make(
app,
(read) => {
read($socket);
return read($connection);
},
{ name: "status" },
);
// One room's messages, read through the atom.
const messagesIn = Computed.fn(
app,
(read, roomId: string) => {
read($socket);
return read($messages.rows).filter((message) => message.roomId === roomId);
},
{ name: "messagesIn" },
);
const setConnection = (state: "connecting" | "open" | "closed") => {
Realm.update(app, (_read, write) => write($connection, state));
};
const receive = (data: unknown) => {
const event = parseEvent(data);
if (event === undefined) {
// The host's error sink, which a realm made without onError uses too.
reportError(new TypeError("chat: dropped an event that is not one"));
return;
}
// One update per event: a reader sees all of it or none of it.
Realm.update(app, (_read, write) => {
switch (event.type) {
case "history":
// A message equal to the one held keeps its row and notifies nobody.
return write.replaceAll($messages, event.messages);
case "message":
return write.upsert($messages, event.message, { at: "end" });
case "deleted":
return write.remove($messages, event.id);
}
});
};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);A request without a socket takes the same shape: a newer request aborts the
older one, and Collection.reconcile keeps unchanged members’ objects.
import { Box, Collection, Realm } from "@frondruntime/sorus";
import { app } from "./realm.ts";
type Load =
| { readonly state: "loading" }
| { readonly state: "loaded" }
| { readonly state: "failed"; readonly error: unknown };
const membersUrl = "https://example.com/members";
interface Member {
readonly id: string;
readonly name: string;
}
const $members = Box.make<ReadonlyArray<Member>>(app, [], { name: "members" });
const $membersLoad = Box.make<Load>(app, { state: "loading" }, { name: "membersLoad" });
const toMember = (value: unknown): Member => {
if (isRecord(value)) {
const { id, name } = value;
if (typeof id === "string" && typeof name === "string") {
return { id, name };
}
}
throw new TypeError("members: a row is not a member");
};
let controller: AbortController | undefined;
// Loads a room's members. A newer call aborts this one, and an aborted call
// writes nothing, so the last call wins. The members stay on screen while
// the next ones load.
const refreshMembers = async (roomId: string): Promise<void> => {
controller?.abort();
const current = new AbortController();
controller = current;
Realm.update(app, (_read, write) => write($membersLoad, { state: "loading" }));
try {
const response = await fetch(`${membersUrl}/${encodeURIComponent(roomId)}`, {
signal: current.signal,
});
if (!response.ok) {
throw new Error(`members: the server answered ${response.status}`);
}
const body: unknown = await response.json();
if (!Array.isArray(body)) {
throw new TypeError("members: the body is not a list");
}
const next = body.map(toMember);
if (current.signal.aborted) {
return;
}
Realm.update(app, (read, write) => {
// Unchanged members keep their object; nothing changed keeps the array.
write(
$members,
Collection.reconcile(read($members), next, {
keyOf: (member) => member.id,
equals: (previous, latest) => previous.name === latest.name,
}),
);
write($membersLoad, { state: "loaded" });
});
} catch (error) {
// An aborted fetch rejects too; the newer call owns the status.
if (current.signal.aborted) {
return;
}
Realm.update(app, (_read, write) => write($membersLoad, { state: "failed", error }));
}
};Rules
- Hang
Source.onObservedon an atom that$statusandmessagesInread, not on$messages.keys:row(key)never readskeys, so a hook there misses a reader of one row. - Write each event in one update, and a history through
write.replaceAllon a collection withequals: a reader sees a history whole, and an unchanged row keeps its object, so a reconnect reruns no reader. - Write
"connecting"in the hook and"closed"in the cleanup:$canSendreads the state without observing the feed, and would offer Send on a closed socket if"open"stayed. - Keep a connection’s state inside the call that opens it, and detach
onclosebefore closing, so a socket from an earlier observation schedules no reconnect. - Check
signal.abortedbefore writing a result or a failure: an abortedfetchrejects, and its failure would overwrite the newer request’s"loading".
With Effect
Program.fromStream (Programs) feeds a value from
an Effect stream that owns the socket.
See also
- Lifecycles:
Source.onObserved, atoms,Source.observe. - Collections:
write.replaceAll,equals,Collection.reconcile. - Updates: an update is synchronous.
- Hooks:
useValueand a list that rerenders one row.