Skip to main content

Reading and subscribing

You wantTakeNot
a value once, nowgetSlotByKey(storeSlot, key).entity, or slotContentService.peekSlotByKey(storeSlot, pk)an effect you dispose straight away
to know whether a key has a value, without minting ithasSlotContentByKey(storeSlot, key)getSlotByKey(storeSlot, key).entity !== undefined, which mints
an identity that must outlive this turnholdSlotByKey(storeSlot, key) … unholdSlot(slot)keeping a getSlotByKey result across a flush()
to be told when a slot moveseffectService.createEffectpolling
a first value now, then every changeeffectService.createAndRunEffectcreateEffect plus a read before it
to be told when one column moveseffectService.createEffect(db, body, [column])an effect over the whole entity
to run something now and on every change of one slotslot.watch(body, columnNames?)an effect you wire by hand
work after every effect of a frame has runsubscribeOnceAfterFrame / subscribeAfterEachFramea write from an effect body
work once the flush has fully endedsubscribeAfterEachFlusha microtask you queue yourself from a tail handler
a cache that empties itselfa slotReleasePolicy at constructiona sweep or a release call of your own

Reading is direct, and it mints​

There is no observable wrapper in this engine. You read the slot.

Setup shared by the examples on this page
import { OIMDB, OIMEffectService, OIMSingleSlotStoreService, OIMUnusedSlotCollectorService, createOIMComputedService, type TOIMBucketSlot, type TOIMBucketSlotsArrayStore, type TOIMComputedSlot, type TOIMSingleSlotStore, type TOIMDisposer, type TOIMEntitySlot, type TOIMStoreKey, createOIMEntityContentService, createOIMSlotCollectionService, OIMPositionalArrayBucketContentService, OIMBucketCommands, createOIMSingleComputedService, type TOIMSlot, type IOIMSlotSubscriptionListener } from '@oimdb/core';

type Card = { id: string; title: string; rank: number };

const db = new OIMDB();
const effectService = OIMEffectService.INSTANCE;
const cardService = createOIMSlotCollectionService({ slotContentService: createOIMEntityContentService<Card>() });
const cards = cardService.createStoreSlot(db);
const byDeckService = createOIMSlotCollectionService({ slotContentService: new OIMPositionalArrayBucketContentService<TOIMEntitySlot<Card>>({ bucketCommands: new OIMBucketCommands({ maxCommandsPerSlot: undefined }) }) });
const byDeck = byDeckService.createStoreSlot(db);

declare const slot: TOIMEntitySlot<Card, TOIMStoreKey>;
declare const bucket: TOIMBucketSlot<TOIMBucketSlotsArrayStore<TOIMEntitySlot<Card>>, TOIMStoreKey>;
declare const pk: TOIMStoreKey;
declare const body: () => void;
declare const render: (card: Card | undefined) => void;
declare const show: (value: number) => void;
declare const poll: () => void;
const cardSlot = cardService.getSlotByKey(cards, 'c1'); // TOIMEntitySlot<Card>, never undefined
cardSlot.entity; // Card | undefined
cardSlot.entity?.title;
cardService.peekSlotByKey(cards, 'c1')?.entity; // the entity or undefined, and nothing minted
cardService.peekSlotByKey(cards, 'c1'); // the slot or undefined, and nothing minted
cardService.hasSlotContentByKey(cards, 'c2'); // false, and nothing minted

cardService.getSlotCount(cards);
for (const s of cardService.getSlots(cards)) { console.log(s.key); }

bucket.getBucketMemberSlots(); // Iterable<TOIMEntitySlot<Card>>
bucket.getBucketMemberSlotCount();

Every read that names a key is the collection service's and takes the store slot of the collection first; a read of a bucket's members is the bucket content service's and takes only the bucket slot.

A key is resolved to its identity once, and from then on every read, write and subscription goes through that object rather than through a lookup. The slot you read from is the slot an effect subscribes to and the slot a bucket files, so nothing downstream has to look the key up again. Keep the slot you already have instead of re-resolving its key in a loop.

getSlotByKey resolves a key to an identity and mints one if the key has none. The mint goes to the db's unused-slot collector, which holds it and gives that hold back at the next flush() — so a read you then hold or subscribe to keeps its identity, and a read you walk away from costs one slot until the end of the turn. See the four doors.

slot.entity is TEntity | undefined because an identity outlives its value: a key you reserved with holdSlotByKey has an identity and no value yet, and clearSlotContent takes the value away and leaves the identity filed for as long as something holds it.

Which read mints​

ReadMints when the key has no identityWhat keeps the mint
getSlotByKey(storeSlot, key), getSingleSlot(storeSlot)the slotthe unused-slot collector, until the next flush()
peekSlotByKey(storeSlot, pk)?.entity, peekSlotByKey(storeSlot, key), peekSingleSlot(storeSlot)nothing—
getEntitiesByKey(indexStoreSlot, key) on an index servicethe bucketthe unused-slot collector
getBucketColumnSlotByKey(indexStoreSlot, key, columnName) on an index servicethe bucket and its column slotthe unused-slot collector
getColumnSlot(slot, name), getAnyColumnSlot(slot)the column slotthe unused-slot collector
holdSlotByKey(storeSlot, key), holdSingleSlot(storeSlot), holdColumnSlot(slot, name)the slotyour hold, until its give-back
hasSlotContentByKey(storeSlot, key), hasSingleSlotContent(storeSlot), isSameKey(key, otherKey), getSlots(storeSlot), getSlotCount(storeSlot), getBucketMemberSlots(bucket), getBucketMemberSlotCount(bucket)nothing—

A computed slot is read through the value service it carries — slot.value — because that refreshes it first. computedSlot.value is the value as of its last refresh. See The compute graph.

The unused-slot collector​

The unused-slot collector holds what a getter minted until the next flush() ends, even when an effect threw. That is what lets a caller read a key that has no value yet and subscribe to it or hold it in the same turn: the subscription lands on the identity every later write uses. The db's collector is db.collectorSlot.unusedSlotCollectorSlot, run by OIMUnusedSlotCollectorService.INSTANCE.

A scope defers the give-back past a frame:

const unusedSlotCollectorSlot = db.collectorSlot.unusedSlotCollectorSlot;
OIMUnusedSlotCollectorService.INSTANCE.run(unusedSlotCollectorSlot, () => {
const first = cardService.getSlotByKey(cards, 'c1');
db.flush();
cardService.getSlotByKey(cards, 'c1') === first; // true: the scope is still open
});

open(collectorSlot) and close(collectorSlot) are the same thing by hand, and they nest; only the close that brings the depth to zero gives the holds back. close without an open throws, because it would sweep slots an outer scope still stands on. run closes from a finally, so a body that throws still gives its holds back. A collector of your own is a bag of holds you give back at once: createOIMUnusedSlotCollectorSlot(), pass each slot you need to holdSlotUntilFlush, and flush it when you are done.

"Live" carries one rule​

getBucketMemberSlots(bucket) hands back the live slots the bucket content service maintains — the Set itself for OIMSetBucketContentService, the list itself for the array-driven one. cardService.getSlots(cards) carries the same rule: it iterates the store the store slot carries rather than a copy of it. So a clearSlotContent, or a removeBucketMemberSlots / addBucketMemberSlots, inside the loop edits the thing the loop is walking. Nothing throws. On an array-driven bucket the slot is spliced out under the loop's own index, so the loop silently skips the slot after each one it removed.

Copy first when the body writes:

const bucketContentService = byDeckService.slotContentService;
for (const entry of Array.from(bucket.getBucketMemberSlots())) {
bucket.removeBucketMemberSlots([entry]);
}

Subscribing is building an effect​

OIMEffectService.INSTANCE.createEffect and createAndRunEffect are how an effect is built, and subscribing is one of the four minting doors: what it leaves behind is a reference to what it minted — the effect itself — so nothing can unfile the identity under the subscriber. An effect is a plain TOIMEffect object with no methods; the stateless OIMEffectService.INSTANCE does all the work on it. Each takes the channel map (db) first.

subscribeEffect(db, body, sourceSlots?, sourceComputeds?, sourceTrackingComputeds?) is createEffect that hands back a disposer instead of the effect; it is what a binding library's subscribe wants.

const effect = effectService.createEffect(
db, () => { render(slot.entity); }, [slot, bucket],
);

effectService.disposeEffect(effect);

The body runs when something it reads has moved, and only then. Both source lists are fixed at construction — a cycle therefore cannot be built, and a derivation's sources cannot include itself. createSourceTrackingEffect(db, body) is the other arm: its body is handed an OIMSourceTracker and names its sources as it reads.

With the fixed lists, the lists you hand in are the whole dependency set: a run costs no tracking, and a slot read in the body but not named in a list does not wake it. createEffect subscribes to and holds every slot you named, every computed you named and every root under those computeds; disposeEffect(effect) gives each back.

Reading a computed from an effect​

const rankService = createOIMSingleComputedService<number>();
const rankOf = rankService.createStoreSlot(
db,
() => slot.entity?.rank ?? 0,
() => ({ sourceSlots: [slot] }),
);
const rankSlot = rankService.holdSingleSlot(rankOf);

const rankEffect = effectService.createEffect(db, () => {
show(rankSlot.value);
}, [], [rankSlot]);

Before deciding whether to run, the effect refreshes each computed it names and then compares revisions: the body runs if a root slot it named directly, or a computed it named, carries a revision after the effect's last run. A write that reaches the computed's sources but leaves its value equal under its sameValueGuard does not advance the computed's revision, so the body does not run.

It hears only what happens after it​

A subscription is told about changes made after the call and about nothing before them — for an entity, a column, a bucket and a derivation alike. A batch does not soften this: writes accumulate until flush(), so subscribing behind a write of the still-open batch is subscribing after that write, and it stays silent.

cardService.writeSlotContentByKey(cards, 'a', { id: 'a', title: 'A', rank: 1 });
const cardSlot = cardService.getSlotByKey(cards, 'a');

effectService.createEffect(db, () => { /* never runs for the upsert above */ }, [cardSlot]);
db.flush();

effectService.createAndRunEffect(db, () => { render(cardSlot.entity); }, [cardSlot]); // runs now

A first value is createAndRunEffect's job. createEffect answers "tell me when this changes"; createAndRunEffect answers "give me it now, and then tell me". If the immediate run throws, createAndRunEffect disposes the effect it built and rethrows, so a failed subscription leaves no hold behind.

A write made later in that same batch is delivered.

Anything that is a slot can be a source: an entity slot, a bucket slot, a column slot, the slot of a standalone record (getSingleSlot(storeSlot)). A computed slot goes in the sourceComputeds list. A store slot is not a slot and is not a source. A service is not a slot and is not a source.

A body may hand back its own undo​

type TOIMEffectBody = () => (() => void) | void;

A body that opens something per run has somewhere to close it: return a function and it is called before the next run and by disposeEffect.

const effect = effectService.createEffect(db, () => {
const timer = setInterval(poll, 1000);
return () => clearInterval(timer);
}, [slot]);

Returning nothing is the ordinary case. Anything returned that is not a function is ignored, so an expression-bodied arrow such as () => set.add(key) is safe.

Subscribing to one column​

const onRank = effectService.createEffect(db, () => { render(slot.entity); }, [slot.holdColumnSlot('rank')]);

It wakes only when that named column moves. A write that changes title does not run it. Use it instead of createEffect(db, …, [slot]) when the body depends on one column of a wide entity that is written often.

A column effect takes the column slot, which goes in the root list of createEffect; the derivation list stays empty. What mints the column identity and holds it is the door one level up — holdColumnSlot(slot, name) on the collection service of an entity or bucket collection, for a slot of a collection or of a single alike, or holdBucketColumnSlotByKey(indexStoreSlot, key, columnName) on an index service for a column across a bucket's members. Each has its give-back — unholdColumnSlot(columnSlot) on the same service.

A computed has columns too: computedService.holdColumnSlot(computedSlot, 'field') returns a TOIMComputedColumnSlot, which goes in the sourceComputeds list and wakes the effect only when that field of the derived value changes (see Computed columns). Every collection service also has getAnyColumnSlot(slot) / holdAnyColumnSlot(slot), a column slot that wakes on any column write to its carrier.

A carrier slot is not released while a column slot is filed on it. A column slot goes when nothing holds it and nothing subscribes to it. Its value is the carrier's state the column stands for (rank.value is slot.entity?.rank; see what a column slot's value is), and a tracked read of it subscribes to the column only.

Column names are type-checked. holdColumnSlot takes the collection's column name type, which createOIMSlotCollectionService<Card> sets to TOIMColumnName<Card>, the keys of Card, so a misspelt column fails to compile. deleteEntityColumns on the entity content service takes readonly TOIMColumnName<TEntity>[].

Watching one slot​

slot.watch(body, columnNames?) is an effect over that one slot, wired for you. It runs body at once and after every frame that changed the slot, and returns the TOIMDisposer that stops it. Its source is the slot, named up front: nothing is tracked, and what the body reads besides the slot does not wake it.

const watchedCard = cardService.holdSlotByKey(cards, 'c1');
const stopTitle = watchedCard.watch(card => { render(card); }, ['title']);

stopTitle();
watchedCard.unholdSlot();
Slotbody getscolumnNames
an entity slot, keyed or singleslot.entity, or undefinedone column name, or the names of a group declared in columnGroups; only a write to them runs it
a computed's slotits valuethe same, over the fields of the value
a bucket slotthe bucket slot; read commands / isWholeListRecorded inside the bodynone

The watch holds what it subscribes to while it stands, like any effect; a slot of yours that must outlive it takes its own hold.

Holding what you subscribe to​

Subscribing takes a reference, and disposeEffect gives it back. If you subscribed to a slot somebody else resolved and you need it to outlive that subscription, take a hold of your own:

slot.holdSlot();
// …
slot.unholdSlot();

Without a hold of your own, an identity whose only reference was your subscription is unfiled when disposeEffect gives the effect's hold back. Any number of readers can hold one identity without knowing about each other; the slot goes when the last of them leaves.

To hold by key, use the keyed form of the same door, which hands back the slot and nothing else:

const heldSlot = cardService.holdSlotByKey(cards, pk);

unholdSlot on a slot whose holdCount is already 0 throws by name, so a give-back is not idempotent — call it exactly once per hold. holdSlot and unholdSlot on a released slot throw too: resolve the key afresh.

Giving many handles back at once​

Keep your own array. There is no scope object for effects in this package:

const disposers: TOIMDisposer[] = [];

disposers.push(effectService.subscribeEffect(db, body, [slot]));

const held = cardService.holdSlotByKey(cards, pk);
disposers.push(() => { held.unholdSlot(); });

for (let i = disposers.length - 1; i >= 0; i--) disposers[i]();

An effect from createEffect has no dispose of its own, so a detached disposer for it is () => effectService.disposeEffect(effect); subscribeEffect hands that disposer back for you. holdSlot and unholdSlot are prototype methods on the owner that read this, so pulling one off type-checks — TOIMDisposer is () => void — and throws a TypeError when it is called. subscribeAfterEachFrame, subscribeOnceAfterFrame and subscribeAfterEachFlush each return a TOIMDisposer closure and are passed directly too.

By keeping the array yourself, you also take on the reverse ordering and the try/catch. For holds on slots alone, a collector slot of your own is the scope (see the unused-slot collector).

Knowing when a slot is watched​

A collection type can be built with a slotSubscriptionListener. It is told when a slot of the collection gets its first subscriber and when it loses its last, which is what a loader needs to fetch a key only while something shows it:


declare function startLoading(slot: TOIMSlot): void;
declare function stopLoading(slot: TOIMSlot): void;

const loadWhileWatched: IOIMSlotSubscriptionListener = {
onSlotFirstSubscribed: watchedSlot => { startLoading(watchedSlot); },
onSlotLastUnsubscribed: watchedSlot => { stopLoading(watchedSlot); },
};

const loadedCardService = createOIMSlotCollectionService({ slotContentService: createOIMEntityContentService<Card>(), slotSubscriptionListener: loadWhileWatched });
  • Only subscribers count. A hold, a getSlotByKey and membership in a bucket do not tell the listener anything.
  • An effect over a computed is subscribed to the computed's root slots, so the collection those roots belong to is told.
  • A subscription to a column is handed over as the column slot itself, through the listener of its entity's collection; its entity is columnSlot.carrierSlot. A listener that tracks entities counts the entity slot and its column slots together.
  • The hooks can run inside a flush (an effect created from an effect body), where writes are refused. Record what to do and act on it from subscribeAfterEachFlush.
  • Bucket, index and computed factories take the same option. Left out, it is OIMNoSlotSubscriptionListener.INSTANCE, which hears nothing.

Interop​

An identity is plain data with no methods. Its owner is the only reference back to the runtime, and operations go through the owner and the effect service, so the API reads effectService.createEffect(db, handler, [slot]) and has no slot.subscribe(handler).

To hand a slot to a binding library, build the pair yourself over what you have:

const subscribe = (onStoreChange: () => void): TOIMDisposer =>
effectService.subscribeEffect(db, onStoreChange, [slot]);
const getSnapshot = () => slot.entity;

Under createOIMInPlaceEntityWriter — the default — slot.entity before and after an update is ===, and a bucket's slots are handed back as the same live object, so a binding that decides "did it change?" by comparing values will never fire. What tells you something happened is your effect running, so such a binding needs a counter bumped inside the handler. Under createOIMReplacingEntityWriter, the entity reference does move on every write, which is the whole reason that strategy ships.

Where to next​