# Lifecycles

> Read when state comes from outside Sorus. Start a listener when a value gains its first observer and stop it after the last, stand for outside state with an atom, hold a value observed, and dispose a realm to end everything it runs.

## 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](../guides/live-data.md)).

```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);
```

`Source.observe` holds a value observed with nothing rendered.

```ts
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.untracked` and 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.dispose` runs 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](../effect/programs.md).

## See also

- [Realms](./realms.md): `Realm.dispose` and what a disposed realm answers.
- [Reacting](./reacting.md): watches and autoruns.
- [Boxes and computed](./boxes.md): atoms and `write.changed`.
- [Async state](../guides/async-state.md): `Computed.fromPromise`.
