Reacting to state
Components & selectors
Re-render on the state you actually use - from a whole store down to a single projected value.
BlexComponentBase
Inherit from BlexComponentBase and call Subscribe(...) in
OnInitialized. The component re-renders whenever a subscribed store changes and
detaches every handler on dispose - there is no StateHasChanged to call and
nothing to clean up.
@inherits BlexComponentBase
@inject CounterStore Counter
<p>Count: @Counter.Count</p>
<button @onclick="Counter.Increment">+1</button>
@code {
protected override void OnInitialized() => Subscribe(Counter);
}
You can subscribe to several stores at once; the call is idempotent per store.
protected override void OnInitialized() => Subscribe(Counter, Todos, Settings);
BlexComponentBase
| Member | Description |
|---|---|
void Subscribe(params ReadOnlySpan<IBlexStore>) |
Re-render on any change to the given stores. Duplicate subscriptions are ignored. |
void Subscribe<T>(IBlexStore, Func<T>, IEqualityComparer<T>?) |
Re-render only when the projected value changes. |
void OwnsSubscription(IDisposable) |
Dispose the given token when the component is disposed. |
TSource Watch<TSource>(TSource) where TSource : INotifyPropertyChanged |
Re-render whenever the source raises PropertyChanged - a mutation, a query created by hand, any view model - until the component is disposed. Returns the source, so the call can initialize a field. |
TimeSpan RenderInterval |
protected. The shortest time between two renders the changes it follows cause - stores, selectors, queries, watched sources. Zero (the default) renders every change; renders for parameters and events are never held back. |
void Dispose(bool disposing) |
protected virtual hook for your own cleanup. Store subscriptions are already detached when it runs - override this instead of implementing IDisposable yourself. |
Selector subscriptions
Subscribe(store) fires on any change to that store. On a store with
many independent fields - or one big collection - that re-renders components that do not care.
Subscribe to a projection instead, and the component only wakes up when the projected value
actually changes.
// Re-renders only when Count changes; a change to Step is ignored.
protected override void OnInitialized()
=> Subscribe(Counter, () => Counter.Count);
Two identical panels, subscribed differently. Change only the Step field and watch which one re-renders.
Subscribe(Store)
Renders on any change to the store.
Subscribe(Store, () => Store.Count)
Renders only when Count changes.
Selective rendering in markup
BlexComponentBase re-renders the whole component, and it has to be the
component's base class - which is a non-starter for an app whose components already derive from
its own base. <BlexSelect> and <BlexView> move the
subscription into the markup instead: only their content follows the store, the component
hosting them never re-renders for it, and it can inherit whatever it likes.
@* Any component - no base class required. *@
@inject CartStore Cart
<header>
<BlexSelect Store="Cart" Selector="() => Cart.Total" Context="total">
<strong>@total.ToString("C")</strong>
</BlexSelect>
</header>
<BlexView Stores="[Cart, Profile]">
@Cart.ItemCount items for @Profile.UserName
</BlexView>
<BlexSelect>renders its content from a projection and re-renders it only when the projection changes - a cart total in a page header, re-rendering when the total differs and not when a line is added that leaves it unchanged.Comparertakes the sameBlexComparersas every other selector.- The selector is re-read whenever the host re-renders, so it may capture the host's parameters (an id, a filter) freely: changes are always compared against what is on screen.
<BlexView>re-renders its content on any change toStoreor any ofStores-Subscribe(store)as markup.RenderInterval- on both, and onBlexComponentBase- caps how often changes re-render: the first change after a quiet interval renders at once, the rest within it collapse into one render of the latest state. For state that changes many times a second (a live feed, a progress counter), where every render is a diff over the wire on Blazor Server. See Throttling renders, below.
The panel's own markup renders once. Change Count and both counters move; change only Step and only the BlexView moves.
<BlexSelect> and <BlexView>
The host renders once; only the content inside each component follows the store.
BlexSelect<TValue>
| Parameter | Description |
|---|---|
IBlexStore Store |
Required. The store whose changes re-evaluate the selector. |
Func<TValue> Selector |
Required. Projects the rendered value; TValue is inferred from it. |
IEqualityComparer<TValue>? Comparer |
What counts as a change. Defaults to EqualityComparer<TValue>.Default; use BlexComparers.Sequence<T>() for a projected collection. |
RenderFragment<TValue>? ChildContent |
The content, rendered with the selected value as its context (rename it with Context="..."). |
TimeSpan RenderInterval |
The shortest time between two renders the projection's changes cause. Zero (the default) renders every change. |
TValue Value |
Not a parameter: the projection's latest value, the one the content renders with. With a RenderInterval it can be ahead of the screen while a throttled render is pending. |
BlexView
| Parameter | Description |
|---|---|
IBlexStore? Store |
A store whose changes re-render the content. |
IEnumerable<IBlexStore>? Stores |
Several, combined with Store. A host re-render passing the same stores re-subscribes nothing. |
RenderFragment? ChildContent |
The content to keep current. |
TimeSpan RenderInterval |
The shortest time between two renders the stores' changes cause. Zero (the default) renders every change. |
Throttling renders
State that changes many times a second - a live feed, a progress counter, a drag - re-renders whatever
follows it that often, and on Blazor Server every render is a diff sent over the wire.
RenderInterval caps it (Fluxor's MaximumStateChangedNotificationsPerSecond): the
first change after a quiet interval still renders at once, and the changes within the interval collapse
into one trailing render of the latest state, so the last change is never missed. It is a parameter of
<BlexSelect> and <BlexView> and a property of
BlexComponentBase, covering the stores, selectors, queries and watched sources it follows.
Renders for any other reason - new parameters, an event handler - are never held back, and the waits run
on the manager's TimeProvider.
@* At most ten renders a second, whatever the ticker does - and the last price always lands. *@
<BlexView Store="Ticker" RenderInterval="TimeSpan.FromMilliseconds(100)">
@Ticker.Price
</BlexView>
<BlexSelect Store="Ticker" Selector="() => Ticker.Price" RenderInterval="TimeSpan.FromMilliseconds(100)" Context="price">
@price
</BlexSelect>
@* Or for the whole component: *@
@code {
protected override void OnInitialized()
{
RenderInterval = TimeSpan.FromMilliseconds(100);
Subscribe(Ticker);
}
}
One async action moves Percent from 0 to 100 in 40 steps, 25 ms apart. Both views show the same store; the left renders every change, the right at most four times a second - and still ends on 100%.
<BlexView Store="Progress">
RenderInterval="250 ms"
Outside components
The same primitive is a plain extension method on IBlexStore, usable anywhere. It
returns a token - dispose it to stop observing.
using var sub = store.Subscribe(
() => store.Count,
count => Console.WriteLine($"count is now {count}"));
// ... later
sub.Dispose(); // stop observing
BlexStoreSubscriptionExtensions
| Member | Description |
|---|---|
IDisposable Subscribe<T>(this IBlexStore, Func<T> selector, Action<T> onChanged, IEqualityComparer<T>? comparer = null, bool fireImmediately = false) |
Invoke onChanged with the new value whenever the projection changes. |
IDisposable Subscribe<T>(this IBlexStore, Func<T> selector, Action<T, T> onChanged, IEqualityComparer<T>? comparer = null, bool fireImmediately = false) |
The same, but the callback receives (previous, current). |
Previous and current
The two-argument overload delivers (previous, current), which is what you want
for transition logic - analytics, animations, "changed from X to Y" logging. This is MobX's
reaction shape.
var sub = store.Subscribe(
() => store.Status,
(previous, current) => _analytics.Track("status-changed", previous, current),
fireImmediately: true);
Custom equality
Both overloads take an optional IEqualityComparer<T>. Supply one when the
projection returns something whose default equality is not what you mean - a collection, for
instance, where you want to compare contents rather than references.
This is the case that quietly defeats selectors. A projection like
() => Contacts.All.Where(c => c.Starred) builds a new object on
every evaluation, so the default reference comparison always reports a change and the
subscription fires on every action - precisely what selecting a projection was meant to
avoid. BlexComparers supplies the two comparers that fix it, the same job
zustand's shallow does.
// Fires on every action: Where(...) is a new object each time.
store.Subscribe(() => store.Contacts.All.Where(c => c.Starred), Refresh);
// Fires only when the starred contacts actually differ.
store.Subscribe(
() => store.Contacts.All.Where(c => c.Starred),
Refresh,
BlexComparers.Sequence<Contact>());
// Order is incidental for a selection of ids -- compare as a set.
store.Subscribe(
() => store.SelectedIds,
Refresh,
BlexComparers.Set<int>());
// Components take the same argument:
Subscribe(Store, () => Store.Visible, BlexComparers.Sequence<Contact>());
BlexComparers
| Member | Description |
|---|---|
BlexComparers.Sequence<T>(comparer?) |
Element-by-element, in order. The default choice for a projected list, filter or LINQ query. |
BlexComparers.Set<T>(comparer?) |
Same elements, order and repetition ignored - for a selection whose order is incidental. |
Both watch the starred contacts. Star and unstar to change the projection; add or remove an unstarred contact to leave it alone but still run it.
Adding an unstarred contact re-runs both projections and produces an identical sequence. Only the left-hand counter moves - and it is the one that would have re-rendered a component for nothing.
fireImmediately
Pass fireImmediately: true to invoke the callback once at subscription time with
the current value, so an observer does not have to seed itself. With the two-argument
overload, previous and current are both the value at subscription.
If that first call throws, the subscription is detached before the exception surfaces - the
caller never received a token, so a handler left attached would be unstoppable.
Two subscriptions on the counter, made when this page opened. A (previous, current) selector over Count with fireImmediately, whose first line is the value at subscription; and Observe(() => Counter.Step), the IObservable form, which delivers the current value when it is subscribed to and then each distinct one. A persisted counter that hydrates after the page opened shows up as a transition too: hydration is a restore, and restores notify. Newest first.
Across stores
BlexManager carries the same pair of overloads for a projection that spans
stores. Without it, a value derived from two stores has to be recomputed on every action of
every store - the cross-store equivalent of re-rendering the whole app on any change.
@inject BlexManager Manager
@inject CartStore Cart
@inject ProfileStore Profile
protected override void OnInitialized()
=> OwnsSubscription(Manager.Subscribe(
() => Cart.Total > Profile.CreditLimit, // spans two stores
overLimit => _banner = overLimit ? "Over your limit" : null));
// The (previous, current) overload and a custom comparer work the same as on a store:
Manager.Subscribe(
() => Cart.Total,
(previous, current) => _analytics.CartValueChanged(previous, current));
The store-level overload only runs when that store changes; the manager-level one
runs after every action in the application. Keep the projection cheap - read
already-memoized [BlexComputed] properties
rather than recomputing over collections inside it.
IObservable, for Rx
Code that already composes change streams with Reactive Extensions - System.Reactive,
ReactiveUI - can take a store's changes as an IObservable<T> and use every Rx
operator on them. Blex itself takes no dependency on Rx: these return the BCL interface.
// System.Reactive: search when the query settles, without a debounce of your own.
using var sub = store.Observe(() => store.Query)
.Throttle(TimeSpan.FromMilliseconds(300))
.DistinctUntilChanged()
.Subscribe(query => store.Search(query));
// Every action, as a stream; descriptors filter it by type.
manager.ObserveActions()
.Where(ctx => OrdersStore.Actions.Place.Matches(ctx))
.Subscribe(ctx => _analytics.Track(ctx.QualifiedName));
store.Observe(selector, comparer?)delivers the current value when an observer subscribes - aBehaviorSubject's semantics - then every value that differs from the last one delivered.- A selector that throws ends the subscription with
OnError, the Rx contract for a failed source, rather than being reported and retried on the next change. The sequence never completes on its own; dispose the subscription. manager.ObserveActions()is every dispatched action, the stream an NgRx effect consumes - filter it with a generated descriptor'sMatches.
Owning other subscriptions
OwnsSubscription(IDisposable) hands any token to the component so it is disposed
along with it - a manager subscription, a selector token you made yourself, anything.
@code {
[Inject] private BlexManager Manager { get; set; } = default!;
protected override void OnInitialized()
{
Subscribe(Store);
OwnsSubscription(Manager.SubscribeTo<OrdersStore>(ctx => Refresh()));
}
}The raw event
Under everything is IBlexStore.StateChanged, a plain Action raised once
per action after the state has settled. Use it directly when you want no machinery at all -
just remember to unsubscribe.
void OnChanged() => Console.WriteLine("something changed");
store.StateChanged += OnChanged;
// ...
store.StateChanged -= OnChanged;
An action that changes five fields raises StateChanged once, not five times,
so you do not need selectors to avoid render storms within an action. Reach for
them when a component should ignore whole categories of change on a shared store.
A selector returning Store.Items (a list) fires whenever the
reference changes - which, if you follow the immutable-assignment rule, is every
time the collection is replaced, even when the contents are equal. Project to something
small and comparable (Items.Count, an id, a formatted string), or pass
BlexComparers.Sequence<T>().
Undo/redo, a DevTools time-travel jump, persistence hydration, an incoming cross-tab
change and the prerender handoff all move state without dispatching an action. A
manager-level projection is re-evaluated after those too - and a
CreateSelector memo is invalidated - so neither keeps reporting a value the
application no longer holds.