# Live data

> Read when state comes from a socket or a server. Open a socket while a value is observed and reconnect after a drop, write each event in one update, refetch without losing row identity, and keep an aborted request from writing.

## 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.

```ts
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);
    }
  });
};
```
```ts
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.

```ts
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.onObserved` on an atom that `$status` and `messagesIn` read,
  not on `$messages.keys`: `row(key)` never reads `keys`, so a hook there
  misses a reader of one row.
- Write each event in one update, and a history through `write.replaceAll`
  on a collection with `equals`: 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:
  `$canSend` reads 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
  `onclose` before closing, so a socket from an earlier observation
  schedules no reconnect.
- Check `signal.aborted` before writing a result or a failure: an aborted
  `fetch` rejects, and its failure would overwrite the newer request's
  `"loading"`.

## With Effect

`Program.fromStream` ([Programs](../effect/programs.md)) feeds a value from
an Effect stream that owns the socket.

## See also

- [Lifecycles](../state/lifecycles.md): `Source.onObserved`, atoms, `Source.observe`.
- [Collections](../state/collections.md): `write.replaceAll`, `equals`, `Collection.reconcile`.
- [Updates](../state/updates.md): an update is synchronous.
- [Hooks](../react/hooks.md): `useValue` and a list that rerenders one row.
