Reactive effects
Ducky.Reactive writes effects as R3 pipelines: a ReactiveEffect receives the stream of actions and the stream of states, and returns a stream of actions to dispatch. Use it where time and streams are the point (debouncing, polling, per-key switching); an Effect<T> is simpler for everything else.
dotnet add package Ducky.ReactiveDebounced search
The state and actions of a search box:
public sealed record Search(string Term, IReadOnlyList<string> Results);
public sealed record SearchTermChanged(string Term);
public sealed record SearchResultsArrived(string Term, IReadOnlyList<string> Results);
public sealed class SearchSlice : Slice<Search>
{
public SearchSlice()
{
On<SearchTermChanged>((state, action) => state with { Term = action.Term });
On<SearchResultsArrived>((state, action) => action.Term == state.Term ? state with { Results = action.Results } : state);
}
protected override Search Initial => new("", []);
}
public interface ISearchApi
{
Task<IReadOnlyList<string>> SearchAsync(string term, CancellationToken cancellationToken);
}The effect waits for a pause in typing, then searches; a newer term cancels the request in flight:
public sealed class SearchEffect(ISearchApi api, TimeProvider time) : ReactiveEffect
{
public override Observable<object> Handle(Observable<object> actions, Observable<StateSnapshot> state) =>
actions.OfActionType<SearchTermChanged>()
.Debounce(TimeSpan.FromMilliseconds(300), time) // a 300 ms pause in typing
.SelectAwait(
async (changed, token) => (object)new SearchResultsArrived(changed.Term, await api.SearchAsync(changed.Term, token)),
AwaitOperation.Switch); // a newer term cancels the request in flight
}Register it with AddReactiveEffect<T>(). The generated AddDuckyGenerated_{Assembly}() registers every accessible reactive effect too (this sample nests its effects in a class named App):
public static DuckyBuilder AddSearch(DuckyBuilder ducky) => ducky
.AddSlice<SearchSlice>()
.AddReactiveEffect<SearchEffect>(); // created from the store's scope, disposed with the store- The store creates the effect from its own scope, with constructor dependencies from DI, and disposes it with the store. Inject
TimeProviderfor every time operator, so tests can drive the clock. OfActionType<T>()matches the exact type. Thestatestream starts with the current state;StoreInitializedreaches a pipeline once, when it starts.- An emission dispatched synchronously in reaction to an action is part of its chain, so an action that re-emits itself stops at the depth guard (64).
Polling while a flag is set
state drives the timer: turning AutoRefresh on starts it, turning it off disposes it.
public sealed class DashboardPolling(TimeProvider time) : ReactiveEffect
{
public override Observable<object> Handle(Observable<object> actions, Observable<StateSnapshot> state) =>
state.Select(static s => s.Get<Dashboard>().AutoRefresh)
.DistinctUntilChanged()
.Select(on => on ? Observable.Interval(TimeSpan.FromSeconds(30), time) : Observable.Empty<Unit>())
.Switch() // turning the flag off disposes the timer
.Select(static object (_) => new RefreshDashboard());
}A switch per key
To cancel a load in flight only when the same item is requested again, group by key and switch inside each group. Use GroupByUntil, never a plain GroupBy: a group that never ends keeps one open subject per key the pipeline ever saw. R3 has neither operator, so here is one to copy:
// R3 ships no GroupBy or GroupByUntil. This operator closes a key's group, and releases it, when its duration observable
// emits or ends (completes or fails, as Rx.NET's GroupByUntil does); the key's next item opens a new group. The source's completion completes every open group. The lock guards the
// dictionary only: nothing is pushed while it is held, because a duration such as Debounce emits on a timer thread under
// its own lock, which a push into the group also takes. A duration that emits while an item is pushed into its group
// closes the group once that push ends, so no item is lost to a closed group. A durationSelector that throws fails the
// group it was opening and releases it, and the error goes on to the subscriber (OnErrorResume).
public static class GroupByUntilOperator
{
public static Observable<Observable<T>> GroupByUntil<T, TKey>(this Observable<T> source, Func<T, TKey> keySelector, Func<Observable<T>, Observable<Unit>> durationSelector)
where TKey : notnull =>
Observable.Create<Observable<T>>(observer =>
{
var gate = new object();
var groups = new Dictionary<TKey, Group<T>>();
// Under the lock: removes the key only while it still maps to this group, so the group closes exactly once.
bool Release(TKey key, Group<T> group) => groups.TryGetValue(key, out var current) && current == group && groups.Remove(key);
Group<T>[] ReleaseAll()
{
lock (gate)
{
Group<T>[] open = [.. groups.Values];
groups.Clear();
return open;
}
}
var subscription = source.Subscribe(item =>
{
var key = keySelector(item);
Group<T>? opened = null;
Group<T> group;
lock (gate)
{
if (!groups.TryGetValue(key, out group!))
{
opened = group = new Group<T>();
groups.Add(key, group);
}
group.Pushing++;
}
if (opened is not null)
{
void Expire()
{
lock (gate)
{
if (opened.Pushing > 0)
{
opened.ExpireRequested = true;
return;
}
if (!Release(key, opened))
{
return; // already closed: Take(1) completes right after it emits
}
}
opened.Items.OnCompleted();
}
try
{
observer.OnNext(opened.Items);
// Subscribed before the first item, which a Debounce duration must see. A duration that ends
// without emitting expires the group too, or the key would keep a dead group forever.
opened.Duration.Disposable = durationSelector(opened.Items).Take(1).Subscribe(_ => Expire(), static _ => { }, _ => Expire());
}
catch (Exception exception)
{
// A throwing durationSelector (or group subscriber) must not leave a group that never closes.
lock (gate)
{
_ = Release(key, opened);
}
opened.Items.OnCompleted(Result.Failure(exception));
throw;
}
}
group.Items.OnNext(item);
lock (gate)
{
group.Pushing--;
if (group.Pushing > 0 || !group.ExpireRequested || !Release(key, group))
{
return;
}
}
group.Items.OnCompleted();
}, observer.OnErrorResume, result =>
{
foreach (var group in ReleaseAll())
{
group.Duration.Dispose();
group.Items.OnCompleted(result);
}
observer.OnCompleted(result);
});
return Disposable.Create(() =>
{
subscription.Dispose();
foreach (var group in ReleaseAll())
{
group.Duration.Dispose();
}
});
});
private sealed class Group<T>
{
public Subject<T> Items { get; } = new();
public SingleAssignmentDisposable Duration { get; } = new();
public int Pushing { get; set; } // pushes in progress, guarded by the lock
public bool ExpireRequested { get; set; } // the duration emitted during a push, guarded by the lock
}
}public sealed class OrderDetailsEffect(IOrdersApi api, TimeProvider time) : ReactiveEffect
{
public override Observable<object> Handle(Observable<object> actions, Observable<StateSnapshot> state) =>
actions.OfActionType<ShowOrder>()
// One group per order id, released after a minute without a ShowOrder for it.
.GroupByUntil(static show => show.Id, group => group.Debounce(TimeSpan.FromMinutes(1), time).AsUnitObservable())
// Within a group, a newer ShowOrder cancels its load in flight; other orders load side by side.
.SelectMany(group => group.SelectAwait((show, token) => new ValueTask<OrderDetails>(api.GetAsync(show.Id, token)), AwaitOperation.Switch))
.Select(static object (details) => new OrderDetailsLoaded(details));
}Failures
- An exception in a pipeline dispatches
EffectFailedwithActionType"reactive", as a system action: strict mode and the unhandled-action check ignore it. A non-terminal error (OnErrorResume) keeps the stream going. - A pipeline that ends with a failure is subscribed again after
RetryDelay(attempt): 1, 2, 4, 8, 16, then 30 seconds, and no more after the eighth attempt. OverrideRetryDelayto change it (nullstops). A successful emission resets the count. - A pipeline that reacts to
EffectFailedmust leave reactive failures out (.Where(static failed => failed.ActionType != "reactive")), or its own failure during an outage would feed it forever.
Idle, prerender and tests
Reactive pipelines are never "running" for the store: WhenIdleAsync, TestStore.Settled() and the prerender seed don't wait for them, even with a request in flight.
- Load a
Prerender<T>slice with anEffect<T>, never a reactive effect (Prerender). - In tests, advance the fake clock (
store.Time.Advance(...)), then check the outcome;Settled()alone doesn't wait for a pipeline.