Effects and concurrency policies
Reducers are pure, so anything that leaves the store (an HTTP call, a timer, storage) runs in an effect. An effect reacts to an action after it was reduced, and dispatches new actions with what it learned.
An effect
The state and actions of a weather panel:
public sealed record Forecast(string City, int Celsius);
public interface IWeatherApi
{
Task<Forecast> GetForecastAsync(string city, CancellationToken cancellationToken);
}
public sealed record LoadForecast(string City);
public sealed record ForecastLoading(string City);
public sealed record ForecastLoaded(Forecast Forecast);
public sealed record ForecastFailed(string City, string Error);
public sealed record Weather(ImmutableDictionary<string, Forecast> Forecasts, ImmutableHashSet<string> Loading, string? Error);
public sealed class WeatherSlice : Slice<Weather>
{
public WeatherSlice()
{
On<ForecastLoading>((state, action) => state with { Loading = state.Loading.Add(action.City), Error = null });
On<ForecastLoaded>((state, action) => state with
{
Forecasts = state.Forecasts.SetItem(action.Forecast.City, action.Forecast),
Loading = state.Loading.Remove(action.Forecast.City),
});
On<ForecastFailed>((state, action) => state with { Loading = state.Loading.Remove(action.City), Error = action.Error });
}
protected override Weather Initial => new(ImmutableDictionary<string, Forecast>.Empty, [], Error: null);
}The effect injects the API and loads a forecast for each LoadForecast:
public sealed class LoadForecastEffect(IWeatherApi api) : Effect<LoadForecast>
{
// A newer LoadForecast for the same city cancels the running one; other cities load side by side.
public override Concurrency Policy => Concurrency.Switch;
protected override object? ConcurrencyKey(LoadForecast action) => action.City;
public override Task Handle(LoadForecast action, EffectContext context, CancellationToken cancellationToken) =>
context.Run(
started: new ForecastLoading(action.City),
work: token => api.GetForecastAsync(action.City, token),
succeeded: forecast => new ForecastLoaded(forecast),
failed: exception => new ForecastFailed(action.City, exception.Message),
cancellationToken);
}context.Run dispatches started, awaits work, then dispatches succeeded(result). Any exception other than this run's own cancellation dispatches failed(exception), an HttpClient timeout included. When the run is cancelled, nothing is dispatched.
Effects are created by the store, with their constructor dependencies from DI, and disposed with it. Register them next to the slices (AddDuckyGenerated_{Assembly}() does both; this sample nests the effect in a class named App):
services.AddSingleton<IWeatherApi>(weatherApi);
services.AddDucky(ducky => ducky
.AddSlice<WeatherSlice>()
.AddEffect<App.LoadForecastEffect>());- Dispatch from an effect through its
context(context.Dispatch,context.DispatchAsyncor a generated helper oncontext), never through an injectedIStore: the context knows which run is dispatching, so a superseded run's results are dropped (DUCKY008 warns on injectingIStoreorIDispatcher). context.Stateis the latest snapshot on every read.- Honour the
cancellationToken: it is cancelled when the run is superseded or the store is disposed. - A handler that throws dispatches
EffectFailed; the store keeps running. await store.WhenIdleAsync()waits until the queue is empty and no effect runs. SetLongRunning => trueon effects that never finish (pollers, listeners), so they don't count.- An effect that dispatches its own trigger after an
await(a poller:Tick→await Task.Delay(interval, context.Time, cancellationToken)→context.Dispatch(new Tick())) is not stopped by the depth guard, which bounds only synchronous chains (MaxDispatchDepth, 64). Such a loop runs until you stop it: give itSwitch, honour the run'scancellationToken, and mark itLongRunningsoWhenIdleAsyncdoesn't wait for it. UnderSwitchthe poller's ownTicksupersedes the run that dispatched it, and an extraTickfrom elsewhere restarts the wait instead of starting a second loop, asMergewould. NotExhaust: the run still holds the slot when it dispatches itsTick, so thatTickis dropped and the poller stops after one round.
public sealed record Tick;
public sealed class PollEffect : Effect<Tick>
{
public static readonly TimeSpan Interval = TimeSpan.FromSeconds(30);
// Switch: the poller's own Tick supersedes the run that dispatched it, and an extra Tick restarts the wait.
// Exhaust would drop the poller's own Tick (its run still holds the slot) and stop the loop after one round.
public override Concurrency Policy => Concurrency.Switch;
// It never finishes: WhenIdleAsync doesn't wait for it.
public override bool LongRunning => true;
public override async Task Handle(Tick action, EffectContext context, CancellationToken cancellationToken)
{
await Task.Delay(Interval, context.Time, cancellationToken);
context.Dispatch(new Tick());
}
}Concurrency policies
Policy decides what happens when the action arrives while an earlier run is still going. The default is Merge.
| Policy | A new action while a run is going |
|---|---|
Merge |
starts another run; both go on |
Switch |
cancels the running one and starts the new one: the newest wins (search boxes, "load the selected item") |
Exhaust |
is ignored until the running one finishes (submit buttons, "refresh") |
Queue |
waits for the running one, then starts: one at a time, in order |
The policy applies per concurrency key. Without ConcurrencyKey, all runs of the effect share one slot. LoadForecastEffect keys by city, so a second LoadForecast("Paris") cancels the first, while LoadForecast("Rome") runs alongside. A key needs value equality, such as a string, a number or a record (DUCKY013).
Several actions in one class
An EffectGroup registers one handler per action type in its constructor, each with its own policy and key:
public sealed record ExportRequested(string Format);
public sealed record ExportFinished(string Format, Uri File);
public interface IExportApi
{
Task<Uri> ExportAsync(string format, CancellationToken cancellationToken);
}
public sealed class ExportEffects : EffectGroup
{
public ExportEffects(IExportApi api)
{
// Exhaust: requests that arrive while an export runs are ignored.
On<ExportRequested>(async (action, context, cancellationToken) =>
{
var file = await api.ExportAsync(action.Format, cancellationToken);
context.Dispatch(new ExportFinished(action.Format, file));
}, Concurrency.Exhaust);
}
}Testing with Ducky.Testing shows how to test an effect with fakes for its dependencies.