# Programs

> Read when an app is written as Effect programs. Run an effect per change, stream changes, hold a value observed for a scope, feed a value from a stream, run a feed while its data is read, and hold a section's writes in a stage until it succeeds.

## Example

Programs are the Effect forms of `Realm.watch`, `Source.observe`, and `Stage.apply`, for applications already written in Effect. `@frondruntime/sorus-effect` exports them next to the rest; `Scoped` marks a call that lives for the caller's scope.

```ts
import { Box, Program, Realm } from "@frondruntime/sorus-effect";
import { Effect, Schema } from "effect";
import { app } from "./realm.ts";

const $query = Box.schema(app, Schema.String, "", { name: "query" });
const $results = Box.schema(app, Schema.Array(Schema.String), [], { name: "results" });

const searchAsTyped = Program.watchScoped(
  app,
  (read) => read($query),
  (query) =>
    Effect.gen(function* () {
      // A newer query interrupts this effect, here or in the search.
      yield* Effect.sleep("200 millis");
      const results = yield* searchMessages(query);
      Realm.update(app, (_read, write) => write($results, results));
    }),
);
```

A stream feeds a value the same way.

```ts
import { Computed, Program } from "@frondruntime/sorus-effect";
import { Effect, Schedule, Stream } from "effect";
import { app } from "./realm.ts";

const onlineLabel = Effect.gen(function* () {
  // No count until the stream emits, then its latest count. The poll runs
  // only while $onlineCount is observed. Losing the last observer resets it
  // to undefined, so a stale count never shows as current.
  const $onlineCount = yield* Program.fromStream<number | undefined>(
    app,
    Stream.fromEffectSchedule(fetchOnlineCount, Schedule.spaced("30 seconds")),
    undefined,
    { name: "onlineCount" },
  );
  return Computed.make(app, (read) => {
    const count = read($onlineCount);
    return count === undefined ? "" : `${count} online`;
  });
});
```

## Rules

- No program requires a service for the realm: `Program.watchScoped` and `Program.fromStream` take it first, and `Program.changes`, `Source.observeScoped`, and `Program.whileObserved` take it from the observable. Only a decoded `Model.Schema` requires `RealmService` ([Classes](./classes.md)).
- A `Program.fromStream` value is the stream's latest element while observed and `initial` otherwise. The stream's error type is `never`: a failure a screen shows is an element, made with `Stream.catch`, and the value keeps it until the last observer leaves.
- A `Program.whileObserved` run ends when its program returns, though the value is still observed; the next run starts after the last observer leaves and another arrives. A feed ends on the stream it runs.
- `Program.whileObserved` and `Program.fromStream` keep the services of the program that called them, not of the code that observes later. Provide a service before the call.
- Write several values per element from `Program.whileObserved`, in one update: `Program.fromStream` publishes each element in an update of its own, so a reader of two such values sees them disagree.
- Choose the owner of the lifetime: observation (`Program.fromStream`, `Program.whileObserved`) for data shown only while read, a fiber for a feed kept whether shown or not, a scope for a command that runs to its end.
- Stop a program by closing its scope, not by keeping stop functions: the scope runs every release in reverse order, also when the program fails or is interrupted.

## Answers

| Call | Answers |
| --- | --- |
| `Program.watchScoped(realm, (read) => ..., (value, previous) => effect, { equals?, name?, scheduler?, immediate? })` | Starts `Realm.watch` in the caller's scope. A new value interrupts the running effect; a defect is logged at the error level and the watch keeps running. |
| `Program.changes($x)` | A stream of the current value of a box or computed value, then each change; a slow consumer skips to the newest. Ends when the realm is disposed. |
| `Program.updates(realm)` | A stream of each `Realm.onUpdate` record from the next update on, none skipped. Ends when the realm is disposed ([Changes](../state/changes.md)). |
| `Source.observeScoped($x)` | Holds a box, computed value, or atom observed until the scope closes, so its hooks keep running with nothing rendered ([Lifecycles](../state/lifecycles.md)). |
| `Program.whileObserved($x, program)` | Runs `program` while `$x` is observed, each run in a scope of its own, interrupted when the last observer leaves. A defect is logged and the next observation runs it again. |
| `Program.fromStream(realm, stream, initial, { equals?, name? })` | A read-only value, released with the scope. The stream runs only while the value is observed, restarts on the next observation, and resets the value to `initial` when the last observer leaves. `equals` defaults to `Object.is`. |
| `Program.fromEffect(realm, effect, initial, { equals?, name? })` | `Program.fromStream` over one effect, run again on each first observer. Its error type is `never`; a defect is logged. |
| `Realm.scoped(options?)` | A realm disposed with `Realm.dispose` when the scope closes, after the programs started in that scope. `Layer.effect(RealmService, Realm.scoped())` makes a layer ([Realms](../state/realms.md)). |
| `Stage.scoped(realm, (stage) => section, { name?, conflicts?, visible?, guess? })` | The section's value, with its stage applied on success; a failure, defect, or interruption drops it. With `conflicts: "fail"`, a changed read fails with `StageConflictError`. `visible` and `guess` show the writes meanwhile ([Stages](../state/stages.md)). |
| `Stage.scoped(stage, (child) => section, { name? })` | A savepoint over `stage`: a failure drops only the child, and each `Effect.retry` attempt opens a fresh one. |

## See also

- [Reacting](../state/reacting.md): `Realm.watch` and `Realm.autorun` without Effect.
- [Stages](../state/stages.md): conflicts, replay, and visible stages.
- [Live data](../guides/live-data.md): a socket feed into a collection.
- [Testing](../guides/testing.md): a test realm and `TestClock`.
