Skip to main content

telar_reactive_core/
effect.rs

1use crate::runtime;
2
3/// A live subscription. Dropping it deregisters the effect, so the closure runs once and never again — which
4/// looks exactly like a working binding until the value it derives is expected to move. Bind it to something
5/// that lives as long as the work should: a struct field, a returned value, or a `let` the reader captures.
6#[must_use = "dropping the handle deregisters the effect: it runs once and then stops. Bind it (a struct \
7              field, a returned value, a captured `let`) for as long as the subscription should last, or use \
8              `memo`, whose handle is `Rc`-backed and kept alive by whoever reads it."]
9pub struct Effect {
10    id: runtime::EffectId,
11}
12
13impl Drop for Effect {
14    fn drop(&mut self) {
15        runtime::deregister_effect(self.id);
16    }
17}
18
19pub fn effect(f: impl Fn() + 'static) -> Effect {
20    let id = runtime::register_effect(Box::new(f));
21    runtime::run_effect(id);
22    Effect { id }
23}