Skip to content

Reacting to state

Cross-store coordination

Let one store react to another's actions without either of them knowing the other exists.

BlexManager

The manager aggregates every registered store into one global state tree, runs the middleware pipeline, feeds the DevTools bridge and applies time-travel snapshots. Most application code never touches it - you inject stores. You reach for the manager when you need coordination, a global snapshot, or dynamic registration.

Registry

Member Description
IReadOnlyList<IBlexStore> Stores Every registered store.
IBlexStore? GetStore(string name) The store registered under that name ("counter", "counter:left"), or null.
TStore? GetStore<TStore>() The first registered store of that type, or null. With several scoped instances, which is first is unspecified - look one up by name.
void Register(IBlexStore) Adds a store. Idempotent. Captures its initial state so ResetState() has somewhere to return to.
void Unregister(IBlexStore) Removes a store; it keeps working, but its actions are no longer observed.
BlexStoreScope<TStore> CreateScope<TStore>(TStore, string? key) Registers one instance among several, as "{name}:{key}"; disposing the scope unregisters and disposes it. See Scoped stores.
event Action<IBlexStore>? StoreRegistered / StoreUnregistered Raised as stores join and leave. Persistence uses them to hydrate a late store and to write the save a leaving one still owes.
Task DispatchAsync(string qualifiedName, JsonObject? payload) Dispatches an action by name with a JSON payload, through its generated wrapper. See Dispatching by name.
TimeProvider TimeProvider The clock for action timestamps, debounced effects and debounced saves. Swap in a fake one in tests. See Testing.
void ResetAll() Resets every registered store to its registered state, each as its own normal ResetState action. Stores already holding that state are skipped; one that fails is reported and skipped, and the rest still reset.

Observation

Member Description
event Action<BlexActionContext>? ActionDispatched Raised after every action, once the per-store event has fired. Prefer Subscribe, which isolates handler exceptions.
IDisposable Subscribe(Action<BlexActionContext>, Func<…, bool>? filter) Observe actions, optionally filtered. Handler exceptions are caught and reported.
IDisposable SubscribeTo<TStore>(Action<…>) Only actions from that store type.
IDisposable SubscribeToAction<TStore, TPayload>(BlexAction<TStore, TPayload>, Action<TStore, TPayload>) One action, by its generated descriptor (OrdersStore.Actions.Place). The handler gets the dispatching store and the typed payload. A BlexAction<TStore> overload takes Action<TStore>. See Typed actions.
IDisposable SubscribeToAction(string, Action<…>) Matches the bare name ("Increment") or the qualified name ("counter/Increment").
IDisposable SubscribeAsync(Func<…, Task>, Func<…, bool>? filter) An async reactor. The task is observed; failures are reported rather than left unobserved.
IDisposable Subscribe<T>(Func<T> selector, Action<T>, IEqualityComparer<T>?, bool fireImmediately) Fires only when a projection spanning stores changes. An Action<T, T> overload delivers (previous, current). Re-evaluated after restores too. See Subscriptions.
BlexSelector<T> CreateSelector<T>(Func<T>) A lazy, memoized derived value over the whole tree - [BlexComputed] lifted to the manager. Read .Value; it recomputes at most once per action, and only when something reads it. It subscribes to nothing; disposing it drops the memoized value.
BlexSelectorFamily<TArg, T> CreateSelectorFamily<TArg, T>(Func<TArg, T>, int maxSize = 128, IEqualityComparer<TArg>?) A selector per argument, read with family[arg]: each memoized like a selector, evicted least recently used beyond maxSize. Remove, Invalidate, Clear, IsValid(arg), Count.
event Action<BlexActionErrorContext>? ActionFailed Raised when an action body throws. The exception still propagates. See Middleware.

Global state

Member Description
JsonObject CaptureGlobalState() Builds the whole tree: { "storeName": { …state… }, … }.
void RestoreGlobalState(JsonObject) Applies a tree to every store without recording actions. A slice that fails to deserialize is reported and skipped; the other stores still restore.
event Action? StateRestored Raised after state moved without an action: once per RestoreGlobalState (undo/redo, time travel), and once per store for hydration, a cross-tab change, the prerender handoff or RestoreState. Cross-store selectors and subscriptions re-evaluate on it.
event Action<IBlexStore>? StoreRestored Raised ahead of StateRestored with each store a restore moved - every store of a RestoreGlobalState, or the one store of a single restore. Persistence writes back just that store on it, and undo/redo compares just its slice.
Func<JsonObject, JsonObject>? DevToolsStateSanitizer Applied to the tree before it reaches DevTools. See DevTools.
Func<string, string>? DevToolsActionSanitizer Applied to the action label before it reaches DevTools.
Action<BlexError>? OnError Sink for isolated pipeline failures. See Error isolation.

Subscribing to actions

Subscribe and its filtered variants are the building block for coordination: react to one store's action and drive another. Handler exceptions are isolated and routed to OnError, so a misbehaving reactor cannot break dispatch for everyone else.

// Everything from one store type
manager.SubscribeTo<CounterStore>(ctx => Console.WriteLine(ctx.QualifiedName));

// One action, by its generated descriptor: the handler gets the store that dispatched it and
// the payload as the type the action takes. A rename is a build error, not a silent no-op.
manager.SubscribeToAction(CounterStore.Actions.Increment, counter => _analytics.Track("increment"));
manager.SubscribeToAction(OrdersStore.Actions.Place,
    (orders, order) => _analytics.Track("order", order.Item, order.Quantity));

// ...or by bare or qualified name
manager.SubscribeToAction("Increment", ctx => _analytics.Track("increment"));
manager.SubscribeToAction("counter/Increment", ctx => { });

// Anything, with your own filter
manager.Subscribe(
    ctx => _log.Add(ctx.QualifiedName),
    filter: ctx => ctx.Args.Count > 0);

// Dispose the returned token to stop observing.
Live: Orders notify, without knowing about notifications

Placing an order dispatches only orders/Place. A manager subscription - registered by this page - turns it into a notification.

orders 0 orders · 0 units

No orders yet.

notifications 0 unread

Nothing yet.

The Inspector's feed shows both actions: orders/Place first, then notifications/Push dispatched by the reactor.

The action context

Every observer receives a BlexActionContext describing what just happened.

BlexActionContext

Member Description
IBlexStore Store The store that produced the action.
string ActionName The bare name, e.g. "Increment" or "Set Count".
string QualifiedName "storeName/ActionName".
IReadOnlyList<BlexActionArg> Args The captured parameter name/value pairs. Empty for parameterless actions; a Set X carries the assigned value.
int Sequence Monotonic action number.
DateTimeOffset Timestamp When the action completed, in UTC.
JsonObject GlobalState The whole state tree immediately after the action. Captured lazily on first access.
bool IsNested Whether it ran inside the body of another action - cart.Checkout() calling orders.Place(). It is recorded in its own right, but a replay skips it, since replaying the outer action runs it again. An action a subscriber dispatches in reaction is not nested: the one it reacts to has finished.
Read GlobalState synchronously

GlobalState is captured lazily on first access, because serializing every store is expensive and most observers never need it. Read it inside your handler: reading it later - after further actions have run - would capture their state instead. Treat the returned tree as read-only; every observer of that action shares the instance.

Async reactors

SubscribeAsync lets a reactor start async work - typically an effect on another store. The returned task is observed, so a failure is reported through OnError rather than surfacing as an unobserved exception.

manager.SubscribeAsync(
    async ctx => await profileStore.Reload(),
    filter: ctx => ctx.QualifiedName == "auth/SignIn");
Watch for reaction loops

A reactor that dispatches an action which its own filter matches will recurse until the stack gives out. Keep reactors one-directional, or guard them with a flag. Blex freezes the in-flight snapshots of actions still being observed before a reactor's follow-up action mutates state, so attribution stays correct - but it will not stop a genuine loop.

Waiting for a condition

A reactor answers "every time this happens". A workflow often needs "once, when this holds": the checkout that waits for sign-in, the import that waits for both lookups to load. manager.WhenAsync(condition, ct) completes at once when the condition already holds, and otherwise after the first change - an action, a restore, an effect starting or finishing - that makes it true (MobX's when, Redux Toolkit's listener condition). A change counts as soon as it is notified, even inside an async action that is recorded only when it ends - so an effect can wait for something its own store's actions do.

[BlexEffect]
private async Task OnCheckout(CancellationToken ct)
{
    await _manager.WhenAsync(() => _session.IsSignedIn, ct);   // shows the sign-in dialog meanwhile
    await _api.CheckoutAsync(Lines, ct);
}

It lets go of the pipeline as soon as it completes or is cancelled, and a condition that throws faults the task rather than being retried - the caller asked for it.

Live: Wait for three orders

Start waiting, then place orders - here or in the demo above. The wait completes on the action that makes the condition true, not before and not on a timer; with three already placed it completes at once. Cancel stops the wait.

orders/Count 0
The wait not waiting

Derived values that span stores

A subscription answers "tell me when this changed". The other half of the problem is "give me this value, cheaply, from several places at once" - and that is what [BlexComputed] does inside one store. CreateSelector lifts it to the manager: a lazy, memoized projection over the whole tree that recomputes at most once per action, however many readers ask for it.

// Created once, read from anywhere.
var summary = manager.CreateSelector(
    () => $"{orders.Units} unit(s) · {notifications.Unread} message(s)");

summary.Value;   // computes
summary.Value;   // cached
orders.Place("Widget", 2);
summary.Value;   // recomputes, once, for every reader

summary.Dispose();   // drops the memoized value; there is no subscription to undo

// In a component, let the base class own it:
protected override void OnInitialized()
{
    _summary = Manager.CreateSelector(() => Orders.Units + Cart.Lines.Count);
    OwnsSubscription(_summary);
}
Live: One computation, three readers

Every card below reads the same selector. Place an order and watch the computation counter move once, not three times - and not at all until something reads it.

Reader A 0 unit(s) · 0 message(s)

Reader B 0 unit(s) · 0 message(s)

Reader C 0 unit(s) · 0 message(s)

Projection ran 1 time(s)
Renders of this page 1
Subscribe pushes, CreateSelector pulls

Subscribe(selector, …) evaluates eagerly after every action so it can tell one observer that the value moved - use it when something must happen. CreateSelector evaluates lazily and shares the result - use it when something must be read. An action whose result nobody reads costs a flag write. It subscribes to nothing - it compares a version the manager stamps on every change - so disposing it (or handing it to OwnsSubscription) just drops the memoized value.

A derived value that takes an argument - the line with this id, the total of that category - is a family: CreateSelectorFamily memoizes one value per argument, each recomputed at most once per change, and keeps at most maxSize of them (128 by default), dropping the least recently read. A selector per id created by hand would keep every id the list ever showed alive; Remove(id) drops one as soon as its entity is gone.

// One memoized value per order id; at most 500 ids held, least recently read dropped first.
var lineTotal = manager.CreateSelectorFamily(
    (int orderId) => orders.Find(orderId).Units * catalog.PriceOf(orderId),
    maxSize: 500);

lineTotal[42];   // computes for 42
lineTotal[42];   // cached
lineTotal[7];    // computes for 7, independently

orders.Cancel(42);
lineTotal.Remove(42);   // its entity is gone: drop it now rather than wait for eviction
Live: One memoized value per order

Each order below is read through a selector family - twice per row, as two components showing the same line would. A family member computes once per change for its id, however many readers it has; the family holds at most five ids and drops the least recently read beyond that. Cancel last removes the cancelled order's member at once.

No orders yet.

Computations 0
Members held (Count / MaxSize) 0 / 5

The list shows the last 5 orders, so the family never has to evict one it is still showing. Any change recomputes each member at most once - placing an order runs the members that are read again, not one per reader.

Where to put the wiring

Three practical options, in rough order of preference:

  • A component that owns the lifetime - OwnsSubscription(...) in OnInitialized. Good when the coordination only matters while some part of the UI is alive. This page does exactly that.
  • Middleware - register an IBlexMiddleware that reacts in OnAction. Good for app-wide, always-on rules. See Middleware.
  • A coordinator service - a scoped service that subscribes in its constructor and disposes its tokens. Resolve it once at startup so it exists.

Dynamic registration

Stores register themselves when first resolved from DI, and <BlexProvider> registers everything up front. For a lazily-loaded feature you can register and unregister by hand. An unregistered store keeps working standalone - its actions simply stop being observed. A persistent store registered after startup is hydrated as it registers, and one that leaves writes any debounced save it still owes first.

var featureStore = new FeatureStore();
manager.Register(featureStore);      // now observed: middleware, DevTools, history, persistence

// ... when the feature is torn down
manager.Unregister(featureStore);    // still usable, just no longer observed

For a second instance of a store that is already registered - one per dialog, one per tab - use CreateScope, which gives each instance its own name. See Scoped stores.

Single-threaded by design

The manager is built for single-threaded dispatch, matching Blazor's rendering model. Its internal lock protects the store registry and global-state capture only; the pipeline itself - the sequence counter, middleware, DevTools - assumes actions are not dispatched concurrently. If you dispatch from several threads, coordinate externally.

An unhandled error has occurred. Reload 🗙