Skip to content

Core concepts

Computed state

Derived values that recompute only when they have to - when the state they read changes.

The convention

Mark a parameterless method named ComputeXxx() or GetXxx() with [BlexComputed] and the generator emits a memoized public property Xxx. The value is calculated on first read, cached, and thrown away the moment a [BlexState] property it reads changes.

[BlexStore(Name = "cart")]
public partial class CartStore
{
    [BlexState] private IReadOnlyList<CartLine> _lines = [];
    [BlexState] private decimal _discountRate;

    [BlexComputed] private decimal ComputeSubtotal() => Lines.Sum(l => l.Total);

    // Computed values may build on other computed values.
    [BlexComputed] private decimal ComputeTotal() => Math.Round(Subtotal * (1 - DiscountRate), 2);

    [BlexComputed] private int ComputeItemCount() => Lines.Sum(l => l.Quantity);
}

Which becomes, in the generated partial:

Generated
private bool __SubtotalValid;
private decimal __SubtotalValue = default!;

public decimal Subtotal
{
    get
    {
        if (!__SubtotalValid)
        {
            __SubtotalValue = ComputeSubtotal();
            __SubtotalValid = true;
        }
        return __SubtotalValue;
    }
}

// A restore, a reset, a rollback, an effect's loading flags: every computed value goes stale.
protected override void InvalidateComputed()
{
    __SubtotalValid = false;
    __TotalValid = false;
    __ItemCountValid = false;
}

// A property setter: only the computed values that read that property -
// Total reads DiscountRate itself and Lines through Subtotal.
protected override void InvalidateComputed(string? propertyName)
{
    switch (propertyName)
    {
        case "Lines":
            __SubtotalValid = false;
            __TotalValid = false;
            __ItemCountValid = false;
            break;
        case "DiscountRate":
            __TotalValid = false;
            break;
        default:
            InvalidateComputed();
            break;
    }
}

Memoization in practice

Reading a computed property ten times evaluates it once. Only a change to the state it reads makes it stale. The counters below are incremented inside the compute methods, so they show exactly how often each one actually ran.

Live: Count the evaluations

Read the values repeatedly - the counters stay put. Change a quantity and both tick over exactly once; toggle the discount and only Total does, since Subtotal never reads it.

Subtotal $37.00
Total $37.00
Items 3
Subtotal evaluated 1×
Total evaluated 1×
  • Blex T-shirt $24.00 each 1
  • Sticker pack $6.50 each 2

Composing computed values

A computed method may read other computed properties. ComputeTotal() above reads Subtotal, so the first read of Total after a change to Lines evaluates both, in dependency order, with no wiring on your part. After a change to DiscountRate only Total runs again, against the Subtotal still memoized - the demo above shows exactly that.

A write invalidates only what reads it

The source generator reads each computed method's body: a write to DiscountRate invalidates the computed values that read DiscountRate (or its backing field), directly or through another computed - not one derived from Lines alone. A computed that reads state the generator cannot follow - through a helper method of the store, a service field, a primary-constructor parameter, this passed along, an effect's flags - is invalidated by every write, as all were before. Only reads count: a statement that just writes another member - the demo's SubtotalEvaluations++ - does not make the computed depend on it. Keep an expensive computed's reads in its own body (or in other computeds) and it recomputes only when its inputs move. What it reads has to change through its property, the way all state does: a backing field written directly or a list changed in place is a write nothing sees - not even by accident, through another field's write, as before.

Read inside an action, it already sees the action's writes

An action batches its notification until it finishes, but not its invalidation: every write marks the computed values stale on the spot. Validation after a write - Balance -= amount; if (Doubled < 0) throw ... - reads the new value, never the one memoized before the action began.

Rules

  • The method must be parameterless - a computed value backs a property, so there is nowhere to pass arguments (BLEX004).
  • The name must start with Compute or Get and have something after it (BLEX003).
  • It must be an instance method, not static (BLEX008).
  • It must not be generic - a property cannot carry type parameters (BLEX014).
  • It must return a value - a void method leaves the property nothing to memoize (BLEX017).
  • The generated property name must not collide with anything else on the store (BLEX005).
  • Any other return type is allowed, including collections and records.

Computed values are not serialized

Only [BlexState] fields go into SerializeState(). Computed values are derived, so they are recalculated after a restore rather than stored - which means a time-travel jump or a rehydrate can never leave a derived value out of sync with the state it came from.

Keep compute methods pure

A compute method should read state and return a value. Do not mutate state or start async work in one: it runs lazily, at unpredictable times, from inside a property getter. (The evaluation counters in the demo above break that rule deliberately, to make the memoization visible.)

An unhandled error has occurred. Reload 🗙