zgui

Stores and selectors

Per-field subscriptions for struct-shaped state, keyed collections, and a selector that updates two rows instead of all of them.

A signal holding a struct wakes every reader when any field changes, and a signal holding a selection wakes every row when the selection moves. A store gives each field of a struct its own subscription. A selector gives each row its own subscription to the selection.

Create a store

With a plain signal, both of these holes subscribe to the whole struct:

#[derive(Clone, Debug, PartialEq)]
struct Settings {
    title: String,
    width: u32,
}

let settings = RwSignal::new(Settings { title: "zgui".to_owned(), width: 800 });

label {{move || settings.get().title.clone()}}
text  {{move || settings.get().width.to_string()}}

Writing width re-runs both. The title hole changes nothing on screen, but it still runs and clones the struct, and that cost grows with the number of readers and the size of the struct. A store keeps the struct shape and gives each field its own subscription:

use zgui::reactive::store::reactive_stores;   // required, see below
use zgui::reactive::{Patch, Store};

#[derive(Clone, Debug, PartialEq, Store, Patch)]
struct Settings {
    title: String,
    width: u32,
}

let store = Store::new(Settings { title: "zgui".to_owned(), width: 800 });

let width = store.width();     // a field handle
width.set(900);
assert_eq!(width.get(), 900);

Every module that derives Store must contain use zgui::reactive::store::reactive_stores;. The derive generates reactive_stores::… paths in your crate. Without the import, the build fails with error[E0433]: cannot find module or crate 'reactive_stores' in this scope.

  • #[derive(Store)] on Foo generates a trait FooStoreFields with one accessor per field. In another module, use that trait to call the accessors.
  • #[store(skip)] omits the accessor for a field.
  • Store::new needs T: Send + Sync + 'static. Use Store::new_local for a T that is not Send.
  • Store<T> is Copy and belongs to the current owner, like a signal.

Read store fields in a view

#[component]
fn SettingsPanel(store: Store<Settings>) -> impl IntoView {
    let title = store.title();
    let width = store.width();

    view! {
        column(class = "settings") {
            label {{move || title.get()}}
            text  {{move || width.get().to_string()}}
            control(on:click = move |_| width.update(|w| *w += 100)) {"Wider"}
        }
    }
}

Clicking writes width. The title hole does not run.

Do not read the whole store in a reactive hole. A reader of the store, or of any parent field, re-runs on every write below it. Read the specific field you need.

Pass a field as a prop

When a component needs one field and does not care which store it comes from, take a Field<T> (or ArcField<T>):

#[component]
fn NumberRow(value: Field<u32>) -> impl IntoView {
    view! {
        row {
            text {{move || value.get().to_string()}}
            control(on:click = move |_| value.update(|v| *v += 1)) {"+"}
        }
    }
}

// Caller:
NumberRow(value = store.width().into())

Field converts from a store and from every field handle (Subfield, AtKeyed, …).

Key a collection field

Give a collection field a key, then address its items by key:

#[derive(Clone, Debug, PartialEq, Store, Patch)]
struct Settings {
    title: String,
    #[store(key: u64 = |row: &Row| row.id)]
    rows: Vec<Row>,
}

#[derive(Clone, Debug, PartialEq, Store, Patch)]
struct Row {
    id: u64,
    value: f32,
}

let row = store.rows().at_key(1);
row.value().set(2.0);

Writing one row's value does not wake another row's readers. A structural change (push, remove, retain) wakes every item reader, because positions moved.

Do not index a collection by position. Unkeyed indexing is deliberately not re-exported: writing item 0 also wakes the readers of item 1, and a reader of index 0 panics with index out of bounds once the collection becomes empty. Key your collections.

Replace a whole value with patch

store.patch(new_value) compares the new value with the current one and notifies only the fields that differ:

store.patch(Settings {
    title: "zgui".to_owned(),   // unchanged: wakes nothing
    width: 1200,                // changed: wakes width readers only
    rows,
});

Use it when a whole value arrives at once, such as a loaded file, a network response or an undo step.

When to use a store

SituationUse
Two or three independent valuesseparate signals
One struct with one readerone RwSignal
A struct with many fields and many independent readersa store
A whole value that arrives at oncea store, with patch
A collection whose items change independentlya store with a keyed field
State whose shape is not known ahead of timesignals

Store limitations

  • Parents are always notified. A reader of a parent field re-runs on any write below it.

  • Field bookkeeping only grows. Entries are never removed, so a store suits bounded, schema-shaped state (settings, a theme, a document). Do not key a store by something unbounded.

  • Some helpers are not re-exported. OptionStoreExt (for .unwrap() and .map() on an Option field), Len, DerefField and ArcStore work, but you import them from the engine path:

    use zgui::reactive::store::reactive_stores::OptionStoreExt;

Track a selection with a selector

When every row in a list reads the same selection signal, moving the selection re-runs every row:

let selected = RwSignal::new(0_usize);

// inside each of a thousand rows
class:selected = move || selected.get() == item.id

Only two rows change, but all thousand re-run. A Selector<K> keeps one small signal per watched key, and is_selected(&key) subscribes the caller to that key only:

use zgui::reactive::Selector;

let selected = RwSignal::new(0_usize);
let selector = Selector::new(move || selected.get());

view! {
    for item in move || items.get(), key = |item: &Item| item.id {
        row(
            class = "row",
            class:selected = move || selector.is_selected(&item.id),
            on:click = move |_| selected.set(item.id)
        ) {
            text {{item.label.clone()}}
        }
    }
}

Moving the selection now notifies two keys, the old one and the new one, so two rows re-run instead of a thousand.

MethodWhat it does
Selector::new(source)A selector over a key source. Keys match when they are equal.
Selector::new_with_fn(source, matches)The same, with your own Fn(&K, &K) -> bool, e.g. "is a prefix of".
is_selected(&key)Whether key is selected. Subscribes the caller to that key only.
watched_keys()How many keys are watched now. Useful in tests to check a churned list returns to zero.

K must be Eq + Hash + Clone + Send + Sync + 'static. Selector<K> is Clone.

When watched keys are removed

is_selected registers a cleanup on the current owner, so unmounting a row removes its entry. Reading the same key twice in one scope registers once, and a key watched by two rows stays until both are gone. Ten thousand mount and unmount cycles leave watched_keys() at zero.

Call is_selected inside the row's own scope, which is where a binding runs anyway. With no current owner it panics in debug builds; in release the entry is never evicted.

Next

On this page