Core concepts
Effects
Async work with a loading flag, an error slot, a cancellation method and a concurrency policy - all generated.
The convention
Mark an async method named OnXxx returning Task or
ValueTask with [BlexEffect]. You get a public Xxx(...)
wrapper plus reactive lifecycle properties. The body is still recorded as one named,
time-travelable action.
[BlexEffect]
private async Task OnLoadUser(int id)
{
User = await _api.GetUserAsync(id);
}
// Generated:
// Task LoadUser(int id)
// bool LoadUserIsLoading
// Exception? LoadUserError
Generated for [BlexEffect] OnLoadUser(int id, CancellationToken ct)
| Member | Description |
|---|---|
Task LoadUser(int id) |
The public wrapper. Note that the CancellationToken parameter is not on it - the generator supplies the token. |
bool LoadUserIsLoading |
True while any run is in flight. Reference-counted across overlapping runs. |
Exception? LoadUserError |
The exception from the last run, or null. Cleared at the start of each run. |
void CancelLoadUser() |
Cancels the in-flight run (the most recently started one when runs overlap) and, for a debounced effect, the invocation still waiting out its quiet period. Emitted when the effect takes a CancellationToken or is debounced. |
The wrapper never throws: an exception from the body is captured into XxxError
instead of propagating. That is deliberate - an effect is usually fired from an event handler
where nothing would catch it. The failure still reaches OnActionError,
which is where a crash reporter hears about it.
[BlexEffect] properties
| Property | Description |
|---|---|
string? Name |
An explicit name. A valid C# identifier becomes the wrapper's name and the label; one with spaces is the label only, and the wrapper still comes from the On prefix - exactly as for [BlexAction]. |
BlexEffectConcurrency Concurrency |
What a run started while another is in flight does: Parallel (the default), Latest, Drop or Queue. See Concurrency. |
int DebounceMilliseconds |
Waits for this quiet period before running, restarting the wait on every invocation; only the last of a burst runs. 0 (the default) runs at once. See Debouncing. |
int RetryCount |
How many times a failed run is retried before its exception lands in XxxError. 0 (the default) runs once. |
int RetryDelayMilliseconds |
The wait before the first retry, doubling before each further one, up to 30 seconds. Default 1000; 0 retries at once. |
int TimeoutMilliseconds |
How long one attempt may take before its token is cancelled and it fails with a TimeoutException. 0 (the default) sets no limit. Needs a CancellationToken parameter. |
int ThrottleMilliseconds |
Runs at most once per window: an invocation made sooner than this after the last run started is dropped without a trace, like one Drop ignores. The opposite end of a burst from DebounceMilliseconds, which it cannot be combined with. 0 (the default) never throttles; a replay never throttles either. |
Loading is reference-counted
XxxIsLoading stays true until the last in-flight run
finishes, so overlapping invocations do not flip it off early - click Parallel
in the lab below three times and its running badge stays on until the third run
ends. The flag and the error slot are set through SetEffectState, which notifies the
UI but never records a time-travel action - a spinner turning on is not something you want to
rewind to, nor an undo step.
Cancellation
Give the effect a trailing CancellationToken parameter and the
generator supplies the token itself - it does not appear on the public wrapper - and emits a
CancelXxx() method.
[BlexEffect(Concurrency = BlexEffectConcurrency.Latest)]
private async Task OnSearch(string query, CancellationToken ct)
{
Results = await _api.SearchAsync(query, ct);
}
// Generated:
// Task Search(string query) <- no token on the public signature
// void CancelSearch()
// bool SearchIsLoading
// Exception? SearchError
Cancellation through the effect's own token - from CancelXxx() or
from being superseded in Latest mode - is a normal outcome and never
populates Error. A foreign OperationCanceledException,
such as an HttpClient timeout, or any cancellation in an effect that has no
token parameter, is a real failure and is recorded in Error.
A store is IDisposable, and its container disposes it - a Blazor Server
circuit ending, a test scope closing. That cancels every in-flight effect and stops any
pending debounce timer, so a request started moments before teardown does not carry on
resuming against a dead renderer. It counts as the effect's own cancellation, so it
populates no Error; the store itself stays usable, because disposal ordering
must not be able to strand a final persistence flush.
Concurrency
[BlexEffect(Concurrency = …)] decides what happens when a run starts while another
is still going, mirroring the RxJS flattening operators NgRx effects are built on.
| Mode | RxJS | Semantics | Use it for |
|---|---|---|---|
Parallel default | mergeMap | Every run proceeds concurrently. | Independent fetches. |
Latest | switchMap | A new run cancels the previous one. | Type-ahead search. |
Drop | exhaustMap | New runs are ignored while one is in flight. | Double-click-proof submits. |
Queue | concatMap | Runs execute one at a time, in arrival order. | Ordered writes. |
Each button starts the same 1.2 s job. Click one several times quickly and read the timeline.
Timeline is empty. Try clicking Latest three times in a row, then Queue three times, and compare.
What you should see
- Parallel - three clicks give three
startedlines immediately and threefinishedlines ~1.2 s later. - Latest - each click
cancelleds the previous run; only the last one finishes. - Drop - the second and third clicks produce
dropped; the first run finishes undisturbed. - Queue - the runs start ~1.2 s apart, strictly in the order you clicked.
A run is recorded when it ends, with what its own flow changed - across its awaits, and nothing
else. Three quick Parallel clicks are three entries in the Inspector's feed, in
middleware OnAction, in DevTools and in the undo history, in the order they finished;
a Drop click's dropped note is an entry of its own, and so is
anything you click while a run awaits. Only an action dispatched from inside a run's body
is part of that run's record.
A realistic type-ahead
Latest plus a token is the whole recipe for search-as-you-type: an obsolete
request cannot land after a newer one and overwrite the results.
Type quickly: each keystroke supersedes the previous request. Flip the failure switch to see the generated error slot fill in.
Debouncing
Latest stops a stale response from landing, but it still sends a request per
keystroke. DebounceMilliseconds waits for a quiet period first, so only the
invocation the user actually paused on runs at all. The two compose, and together they are
the complete type-ahead recipe: debounce decides whether to ask, Latest
decides which answer is allowed to land.
[BlexEffect(DebounceMilliseconds = 300, Concurrency = BlexEffectConcurrency.Latest)]
private async Task OnTypeAhead(string query, CancellationToken ct)
{
Query = query;
Results = await _api.SearchAsync(query, ct);
}
The wait happens before anything observable, which is what makes it worth generating rather
than hand-rolling. A superseded invocation never flips XxxIsLoading, never
clears XxxError, is never offered to middleware and records no action - so a
spinner bound to IsLoading does not blink once per keystroke, and DevTools does
not fill up with searches that never happened. A debounced effect's CancelXxx()
also cancels the invocation still waiting out its quiet period - what a Clear button needs, or
the pending search would start a moment after the box was emptied.
Type a word at normal speed. The keystroke counter climbs per character; the request counter climbs once, when you pause.
Every invocation of the same effect shares one gate, whatever its arguments. That is what you want for a search box; if you need one gate per key (say, per row in a grid), debounce at the call site instead.
Retries and timeouts
Networks fail transiently. RetryCount runs a failed body again, waiting
RetryDelayMilliseconds before the first retry and doubling the wait before each
one after it, up to 30 seconds. TimeoutMilliseconds bounds every attempt: one
that overruns has its token cancelled and fails with a TimeoutException - which
is retried like any other failure.
[BlexEffect(RetryCount = 3, RetryDelayMilliseconds = 500, TimeoutMilliseconds = 10_000)]
private async Task OnLoadOrders(CancellationToken ct)
{
Orders = await _api.GetOrdersAsync(ct); // assigned once it has arrived: safe to repeat
}
// attempt 1 fails -> wait 500 ms -> attempt 2 fails -> wait 1 s -> attempt 3 fails
// -> wait 2 s -> attempt 4: its failure is LoadOrdersError
The attempts are one run. XxxIsLoading stays on across them, the action is
recorded once, and only the final failure lands in XxxError and reaches
OnActionError. Cancellation through the effect's own token -
CancelXxx(), a superseding Latest run, the store being disposed -
is never retried: it ends the run, during an attempt or during the wait before the next one.
Pick how many attempts the server fails. Three retries cover up to three failures; the fourth reaches XxxError. Time out twice makes the first two attempts hang instead: each is cut off at 2000 ms with a TimeoutException and retried like any other failure. Cancel ends the run - mid-attempt or mid-wait - and leaves the error slot empty.
A retry runs the body again from the top, so state it changed on a failed attempt is
still there when the next one starts. Assign results once they have arrived, as above,
rather than accumulating them. A timeout needs a CancellationToken
parameter (BLEX023): the token is how an overrunning attempt is told to stop.
Rules
-
The return type must be non-generic
TaskorValueTask(BLEX007). An effect owns the loading and error lifecycle, so there is nowhere to put a return value - write results into[BlexState]fields. Latestwithout aCancellationTokenparameter is warningBLEX009: supersession still marks the run stale, but the superseded body keeps executing because nothing can observe the cancellation.- Effects cannot be
static(BLEX008) or generic (BLEX014), and cannot take by-ref parameters (BLEX013). async voidis rejected: an effect returningvoidisBLEX007like any other non-Taskreturn, and an action isBLEX010- nothing could await it, or know when to record it.DebounceMillisecondscannot be negative (BLEX019), nor canRetryCount,RetryDelayMillisecondsorTimeoutMilliseconds(BLEX022), norThrottleMilliseconds(BLEX027), and an effect cannot both debounce and throttle (BLEX028).TimeoutMillisecondsneeds a trailingCancellationTokenparameter (BLEX023) - the token is how an overrunning attempt is told to stop.
Queue makes each run wait for its predecessor. If a queued effect invokes
itself - directly, or through a subscriber its body triggers - the nested call waits on a
gate that only the outer call can open, and both deadlock.
Every invocation is offered to the middleware and filters on its own - one made while another run
of the same effect still awaits included - and the wrapper asks before it touches anything
observable. So a vetoed invocation never flips XxxIsLoading, never clears
XxxError, never cancels the Latest run in flight and never takes a
Queue slot: the run already going keeps going. An invocation Drop ignores,
or a debounced one a newer call superseded, never reaches the middleware at all - nothing was
dispatched.
The generated wrapper
Roughly what the generator emits for a Latest effect with a token:
private int __SearchPending;
public bool SearchIsLoading => __SearchPending > 0;
private Exception? __SearchError;
public Exception? SearchError => __SearchError;
private CancellationTokenSource? __SearchCts;
public void CancelSearch() => __SearchCts?.Cancel();
private int __SearchVersion;
public async Task Search(string query)
{
// The veto first, before anything observable: a vetoed invocation flips no loading flag,
// clears no error and cancels no run in flight.
var args = IsObserved ? new[] { new BlexActionArg("query", query) } : null;
if (!BeginAction("Search", args))
return;
var version = ++__SearchVersion; // stale runs must not clobber newer error state
__SearchCts?.Cancel(); // Latest: supersede the previous run
var cts = new CancellationTokenSource();
__SearchCts = cts;
var ct = cts.Token;
try
{
BeginEffect(ref __SearchPending);
SetEffectState(ref __SearchError, null);
await DispatchApprovedAsync("Search", () => OnSearch(query, ct), args); // already approved
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
// Our own cancellation: a normal outcome, not an error.
}
catch (Exception ex)
{
if (version == __SearchVersion)
SetEffectState(ref __SearchError, ex);
}
finally
{
if (ReferenceEquals(__SearchCts, cts))
__SearchCts = null;
cts.Dispose();
EndEffect(ref __SearchPending);
}
}
The other options slot into the same shape. DebounceMilliseconds adds a wait on the
manager's clock at the very top, before the veto, which a newer invocation cancels;
Drop returns early while a run is pending; Queue awaits the previous
invocation's gate before clearing the error; and RetryCount /
TimeoutMilliseconds wrap the body in RunEffectAttemptsAsync. Disposing the
store cancels every effect's source through the generated CancelEffects().