Skip to main content

crabshell_reactive/
effect.rs

1//! Effects: code that reruns when what it read changes.
2
3use std::marker::PhantomData;
4
5use crate::handle::{NotSend, handle_impls};
6use crate::runtime::{self, Computed, NodeId};
7
8/// Code that reruns when what it read changes. Every widget binding is one.
9///
10/// Create one with [`Owner::effect`](crate::Owner::effect) or
11/// [`Owner::effect_scoped`](crate::Owner::effect_scoped). A new effect is
12/// queued straight away. Created during a [`Runtime::flush`](crate::Runtime::flush),
13/// for example by another effect, it runs later in that same flush; created
14/// anywhere else, it runs at the next flush. After that it reruns whenever a
15/// signal or memo it read on its last run changes. It stops for good when
16/// its owner is disposed, when its closure panics, or when it is caught in a
17/// dependency cycle. The last two are logged with its debug name.
18pub struct Effect {
19  id: NodeId,
20  _not_send: NotSend,
21}
22
23handle_impls!(Effect);
24
25impl Effect {
26  #[track_caller]
27  pub(crate) fn new(owner: NodeId, mut f: impl FnMut() + 'static) -> Self {
28    let compute = move || {
29      f();
30      Computed {
31        changed: true,
32        leftover: None,
33      }
34    };
35    Effect {
36      id: runtime::create_effect(owner, Box::new(compute)),
37      _not_send: PhantomData,
38    }
39  }
40
41  /// Gives the effect a debug name, such as the widget path of the binding
42  /// it implements. Panic and cycle log lines show it.
43  pub fn named(self, name: impl Into<String>) -> Self {
44    runtime::set_name(self.id, name.into());
45    self
46  }
47}