Concepts
Entities
Entity handles, updates, notify, events and weak handles.
An Entity<T> is a handle to state of type T owned by the application.
State lives in the app, not in your struct, so handles are cheap to clone and
can be shared between views.
let counter: Entity<Counter> = cx.new(|_cx| Counter { value: 0 });
counter.read(cx).value; // &T
counter.update(cx, |counter, cx| { // &mut T plus Context<Counter>
counter.value += 1;
cx.notify(); // re-render views observing it
});Rules that matter in practice:
- Updating an entity that is already being updated panics. Structure code so
one
updatefinishes before another begins on the same entity. cx.notify()marks the entity dirty. Views re-render andcx.observecallbacks fire. Forgetting it is the usual reason a view does not refresh.cx.emit(event)sends a typed event; the entity declaresimpl EventEmitter<MyEvent> for MyEntity {}. Listeners usecx.subscribeand keep the returnedSubscriptionin a_subscriptions: Vec<Subscription>field, since dropping it unsubscribes.entity.downgrade()gives aWeakEntity<T>whoseupdateandread_withreturnanyhow::Result. Use weak handles in long-lived tasks and in any structure where two entities reference each other, or neither is dropped.