Events and Subscriptions
An imperative read returns one promise; it does not continuously update your screen or telemetry. A subscription observes lifecycle events for an exact key and keeps receiving them until you unsubscribe. Use it when your application needs to respond to background refreshes or explicit cache writes outside React’s data hooks.
Start with your application’s shared query instance. Keep the returned cleanup function beside the lifecycle that installs the listener.
Observe a key and clean up
Section titled “Observe a key and clean up”To report failed profile fetches while a screen is active:
const stop = query.subscribe('/profile.json', 'error', (event) => { console.error('Unable to refresh the profile:', event.detail)})Call stop() when the screen or service stops observing this instance. The callback receives an object with detail; the generic parameter describes the payload, not the entire event.
Success events carry values, while start events carry promises. The shipped subscribe overloads also include legacy promise typings for success events. For precise value access, give the listener an explicit SubscribeListener<T> type so the generic event overload can describe the runtime payload:
import { type SubscribeListener } from '@studiolambda/query'
/** Consumes a completed value, not the pending-request promise. */const onResolved: SubscribeListener<Profile> = (event) => { console.log('Current name:', event.detail?.name)}const stop = query.subscribe<Profile>('/profile.json', 'resolved', onResolved)Here Profile is the application’s validated profile shape. CustomEventInit<T> makes detail optional in the exported callback type, even though these runtime emissions supply it. Unsubscribe with stop() as in the first example.
| Event | Runtime detail | When it occurs | Broadcast by emit |
|---|---|---|---|
refetching | Promise<T> | A fetch starts; delivery is queued in a microtask | No |
resolved | T | The owning fetch commits | Yes |
error | unknown | The owning fetch or its expiration calculation fails | No |
aborted | unknown | Explicit abort or fresh replacement, with the supplied reason | No |
mutating | Promise<T> | A mutation is enqueued, including time waiting behind another mutation | No |
mutated | T | A mutation commits | Yes |
hydrated | T | Data is seeded | Yes |
forgotten | T or undefined | A stored item is removed and its old promise has settled | Yes |
Mutation rejection does not emit error; catch its returned promise. A forgotten key without a stored item emits no event. Superseded fetches do not emit completion success/errors over newer writes. The corresponding action promise is the authoritative result for the caller that initiated it.
If you subscribe to refetching while a resolver already exists, Query queues a microtask that emits the pending promise. This replay is not synchronous or an exact-once accounting mechanism; an existing listener can also observe the replay. Do not count events to determine how many network requests were made.
Understand local and global scope
Section titled “Understand local and global scope”Subscriptions belong to the instance’s EventTarget. Keys in another default instance are unrelated, even if their strings match. There is no wildcard key, all-keys subscribe, or global unkeyed error event.
For application-wide error reporting, instrument your fetcher or wrap the application methods that initiate work. For a known group, install one keyed subscription per member and retain all cleanup functions. Enumerating query.keys() gives only currently stored keys, not future keys or every possible request.
query.events() exposes the retained platform event target. Its event names are ${event}:${key}, such as resolved:/profile.json. Direct addEventListener is useful for integration, but still requires an exact name and matching removeEventListener cleanup. Replacing the target through configure does not migrate existing listeners. Prefer subscribe() for ordinary keyed observation.
Wait for a specific operation
Section titled “Wait for a specific operation”When a test or workflow needs one notification, register once() before triggering the action:
const waiting = query.once<Profile>('/profile.json', 'hydrated')query.hydrate('/profile.json', { id: 1, name: 'Ada', role: 'Editor' })const event = await waitingconsole.log(event.detail?.name) // Adaonce() removes its listener when the event arrives. Its optional third argument is an AbortSignal; cancellation removes the listener and rejects with the signal’s reason, including when the signal is already aborted. Give long-lived waits an owner so they do not remain subscribed forever if the event never occurs.
To wait for fetched values rather than a particular completion notification, use next():
const waiting = query.next<{ profile: Profile }>({ profile: '/profile.json' })await query.query('/profile.json', { fresh: true })const result = await waitingconsole.log(result.profile.name)next() waits for refetching and then awaits its promise. It does not initiate a request. It accepts a single string, an array such as next<[Profile, Settings]>([profileKey, settingsKey]), or an object mapping output properties to keys. Array/object forms wait for each key and preserve the corresponding shape. Settings, profileKey, and settingsKey in that signature example belong to your application.
A valid cached read, mutation, or hydration is not a new refetching event. Waiting for it with next() can hang. Register the wait before the triggering work, and supply its optional signal when the workflow may end early. That signal cancels event waits, not a fetch promise already received in an event.
Consume repeated events
Section titled “Consume repeated events”sequence<T>(key, event) is an async generator of event objects. stream<T>(keys) is an async generator of fetched results using the same key shapes as next(). Neither opens a server connection, starts reads, polls, or buffers events while your loop processes a previous value.
For a finite observation, break when your condition is met:
for await (const event of query.sequence<Profile>('/profile.json', 'resolved')) { console.log(event.detail?.name) break}Breaking after a yield runs cleanup. Calling a generator’s .return() while its .next() is waiting does not interrupt that pending wait; .return() queues behind it. For externally cancellable observation, prefer a loop built around once(..., signal) or next(..., signal) rather than relying on generator return to interrupt silence.
Share events between browser tabs
Section titled “Share events between browser tabs”Broadcasting is off by default. Opt in only if every same-origin participant on the channel is allowed to receive the full data. Names separate intended routing, not authorization: other same-origin code that knows the name can send or receive messages. Never put credentials in the name, and do not send secrets just because a channel is scoped.
In browser-only setup, create a channel using non-secret application, tenant, and session labels:
import { createQuery } from '@studiolambda/query'
/** Caller-owned channel; all participants must be allowed to share its data. */const channel = new BroadcastChannel('profile-app:tenant-42:session-7')/** Sends supported events through the supplied channel. */const query = createQuery({ broadcast: channel })/** Receives remote events; omit this manual call when a React provider owns it. */const stopReceiving = query.subscribeBroadcast()Local resolved, mutated, hydrated, and forgotten events send their full payloads. Even forgetting can disclose the removed value. Non-cloneable payloads and other postMessage failures are silently ignored, so successful local actions do not prove delivery. There is no durable log or acknowledgement.
Incoming messages replay local events only: they do not write the receiving instance’s cache and are not rebroadcast. A React listener can receive a value without the local item entry or expiration changing. A later local read can therefore use a different cached value. This facility is event delivery, not a coherent cross-tab replicated cache. If you need reliable convergence, design explicit validation, invalidation, and server reconciliation in your application.
The incoming payload is trusted without runtime schema validation or an event allowlist. Keep untrusted participants off the channel; a routing label is not a defense against same-origin malicious code. Create a new query/channel when accounts, tenants, or sessions change rather than allowing old listeners to receive new-scope data.
When all users have detached, clean up in this order:
stopReceiving()channel.close()subscribeBroadcast() captures the channel used at subscription time, so its cleanup still targets that channel after reconfiguration. With no channel it returns a harmless no-op. A React QueryProvider manages a shared incoming listener while mounted but never creates or closes your channel. Do not close it until every provider and manual consumer is finished.
Emit only when building an integration
Section titled “Emit only when building an integration”emit(key, event, detail) dispatches a lifecycle-shaped event and can broadcast the supported kinds. It does not change the cache. Using emit('profile', 'hydrated', value) instead of hydrate() can leave observers and stored data disagreeing. Use the state-changing methods for normal application work; reserve emit() and the exported BroadcastPayload type for integrations that deliberately own that distinction.