# Selectors

A selection is a value computed from the state that follows its changes. `IStore.Select` returns a `Selection<T>`: read `Value` (or use it where a `T` is expected), and dispose it when you are done.

## Select

Source: https://github.com/phmatray/Ducky/blob/v2/test/Ducky.Docs.Tests/Core/SelectorsGuideTests.cs#L32-L39

```csharp
using var open = store.Select(TodoSelectors.OpenCount.Create(), onChange: count => openBadge = count);
using var selected = store.Select(TodoSelectors.ById.Create(() => selectedId));
using var total = store.Select((Todos todos) => todos.Items.Count, onChange: changes.Add);

await store.DispatchAsync(new TodoAdded(new TodoItem(1, "Write docs", Done: false)));

int openCount = open;           // 1: a Selection<T> converts to T
var title = selected.Value?.Title; // "Write docs"
```

- `Select((Todos todos) => ...)` projects one slice. It skips the projector while that slice's reference is unchanged.
- `onChange` runs after a commit, only when the projected value changed (by `EqualityComparer<T>.Default`, or the comparer you pass). It runs on the thread that reduced the action, which may be a thread-pool thread: in Blazor, Ducky's components marshal to the renderer for you, and your own callbacks must use `InvokeAsync` for UI work.
- `Value` is computed against the current state each time you read it.

## Reusable, memoized selectors

`Selector.Define` combines up to four inputs with a projector. The projector runs again only when an input changed (by reference, or by value for value types):

Source: https://github.com/phmatray/Ducky/blob/v2/test/Ducky.Docs.Tests/Core/SelectorsGuideTests.cs#L6-L16

```csharp
public static class TodoSelectors
{
    // A SelectorDef holds no cache, so a static field is safe.
    public static readonly SelectorDef<int> OpenCount = Selector.Define(
        (StateSnapshot state) => state.Get<Todos>().Items,
        items => items.Items.Count(todo => !todo.Done));

    public static readonly SelectorDef<int, TodoItem?> ById = Selector.Define(
        (StateSnapshot state) => state.Get<Todos>().Items,
        (EntityState<int, TodoItem> items, int id) => items.Find(id));
}
```

A `SelectorDef` holds no cache, so a static field is safe. `Create()` returns a selector with its own single-entry cache, one per subscriber; `Evaluate(state)` computes once without a cache. A definition with an argument takes it as a function in `Create(() => id)`, read on every evaluation, so the selection follows the argument when it changes.

Projectors must be pure, like reducers (DUCKY001 to DUCKY003 apply to them), and may run on two threads at once.
