Skip to main content

Signal

Struct Signal 

Source
pub struct Signal<T>(/* private fields */);
Expand description

Shared, single-threaded reactive state. Cloning shares the same value.

Implementations§

Source§

impl<T> Signal<T>

Source

pub fn with<R>(&self, read: impl FnOnce(&T) -> R) -> R

Read without cloning the value, tracking this dependency. Do not write this signal while the read closure holds its borrow.

Source

pub fn with_untracked<R>(&self, read: impl FnOnce(&T) -> R) -> R

Read without subscribing the current effect.

Source

pub fn update<R>(&self, update: impl FnOnce(&mut T) -> R) -> R

Mutate state, then notify subscribers after releasing the mutable borrow. Always notifies; use set to skip unchanged values. The mutation closure must not read or write this same signal.

Source

pub fn replace(&self, value: T) -> T

Replace the value and notify subscribers, returning the previous value. Unlike set, this needs no PartialEq and always notifies. Dropping the result retires the old value after notification.

Source§

impl<T: Clone> Signal<T>

Source

pub fn get(&self) -> T

Clone the current value and automatically track the read.

Examples found in repository?
examples/memo_workload.rs (line 14)
6fn run(name: &str, cached: bool, consumers: usize, updates: u64, work: u64, group: u64) {
7    let input = signal(0_u64);
8    let computations = Rc::new(Cell::new(0_u64));
9    let renders = Rc::new(Cell::new(0_u64));
10    let compute = {
11        let (input, computations) = (input.clone(), computations.clone());
12        move || {
13            computations.set(computations.get() + 1);
14            let mut n = input.get() / group;
15            for _ in 0..work {
16                n = black_box(n.wrapping_mul(6364136223846793005).wrapping_add(1));
17            }
18            n
19        }
20    };
21    let read: Rc<dyn Fn() -> u64> = if cached {
22        let value = memo(compute);
23        Rc::new(move || value.get())
24    } else {
25        let value = derived(compute);
26        Rc::new(move || value.get())
27    };
28    let subscriptions: Vec<_> = (0..consumers)
29        .map(|_| {
30            let (read, renders) = (read.clone(), renders.clone());
31            effect(move || {
32                black_box(read());
33                renders.set(renders.get() + 1);
34            })
35        })
36        .collect();
37    computations.set(0);
38    renders.set(0);
39    let start = Instant::now();
40    for value in 1..=updates {
41        input.set(black_box(value));
42    }
43    let elapsed = start.elapsed().as_micros();
44    let mode = if cached { "Memo" } else { "Derived" };
45    println!(
46        "{name},{mode},{consumers},{updates},{},{},{elapsed}",
47        computations.get(),
48        renders.get()
49    );
50    assert_eq!(
51        computations.get(),
52        updates * if cached { 1 } else { consumers as u64 }
53    );
54    assert_eq!(
55        renders.get(),
56        if cached { updates / group } else { updates } * consumers as u64
57    );
58    drop(subscriptions);
59}
Source

pub fn get_untracked(&self) -> T

Clone the current value without dependency tracking.

Source§

impl<T: PartialEq> Signal<T>

Source

pub fn set(&self, value: T)

Replace the value, notifying only when it actually changes. Retire the old value after notification, outside the internal borrow. Inside a batch, notification queues observers until the batch completes.

Examples found in repository?
examples/memo_workload.rs (line 41)
6fn run(name: &str, cached: bool, consumers: usize, updates: u64, work: u64, group: u64) {
7    let input = signal(0_u64);
8    let computations = Rc::new(Cell::new(0_u64));
9    let renders = Rc::new(Cell::new(0_u64));
10    let compute = {
11        let (input, computations) = (input.clone(), computations.clone());
12        move || {
13            computations.set(computations.get() + 1);
14            let mut n = input.get() / group;
15            for _ in 0..work {
16                n = black_box(n.wrapping_mul(6364136223846793005).wrapping_add(1));
17            }
18            n
19        }
20    };
21    let read: Rc<dyn Fn() -> u64> = if cached {
22        let value = memo(compute);
23        Rc::new(move || value.get())
24    } else {
25        let value = derived(compute);
26        Rc::new(move || value.get())
27    };
28    let subscriptions: Vec<_> = (0..consumers)
29        .map(|_| {
30            let (read, renders) = (read.clone(), renders.clone());
31            effect(move || {
32                black_box(read());
33                renders.set(renders.get() + 1);
34            })
35        })
36        .collect();
37    computations.set(0);
38    renders.set(0);
39    let start = Instant::now();
40    for value in 1..=updates {
41        input.set(black_box(value));
42    }
43    let elapsed = start.elapsed().as_micros();
44    let mode = if cached { "Memo" } else { "Derived" };
45    println!(
46        "{name},{mode},{consumers},{updates},{},{},{elapsed}",
47        computations.get(),
48        renders.get()
49    );
50    assert_eq!(
51        computations.get(),
52        updates * if cached { 1 } else { consumers as u64 }
53    );
54    assert_eq!(
55        renders.get(),
56        if cached { updates / group } else { updates } * consumers as u64
57    );
58    drop(subscriptions);
59}

Trait Implementations§

Source§

impl Checkbox for Signal<bool>

Source§

fn checked(&self, _: &str) -> bool

Whether the box whose value is choice is checked.
Source§

fn check(&self, _: &str, checked: bool)

The user checked or cleared the box whose value is choice.
Source§

impl<T: FromStr + PartialEq + 'static> Checkbox for Signal<Vec<T>>

Source§

fn checked(&self, choice: &str) -> bool

Whether the box whose value is choice is checked.
Source§

fn check(&self, choice: &str, checked: bool)

The user checked or cleared the box whose value is choice.
Source§

impl<T> Clone for Signal<T>

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<T: FromStr + Display + PartialEq + 'static> TextValue for Signal<T>

Source§

fn text(&self) -> String

The text the control shows.
Source§

fn shows(&self, text: &str) -> bool

Whether the control’s text already shows this value. Such an edit is never written back, which keeps the cursor and partial input intact.
Source§

fn edit(&self, text: String)

Apply the control’s text after a user edit.
Source§

fn touch(&self)

The control lost focus.

Auto Trait Implementations§

§

impl<T> !RefUnwindSafe for Signal<T>

§

impl<T> !Send for Signal<T>

§

impl<T> !Sync for Signal<T>

§

impl<T> !UnwindSafe for Signal<T>

§

impl<T> Freeze for Signal<T>
where Rc<SignalInner<T>>: Freeze,

§

impl<T> Unpin for Signal<T>
where Rc<SignalInner<T>>: Unpin,

§

impl<T> UnsafeUnpin for Signal<T>
where Rc<SignalInner<T>>: UnsafeUnpin,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<S, T> Upcast<T> for S
where T: UpcastFrom<S> + ?Sized, S: ?Sized,

Source§

fn upcast(&self) -> &T
where Self: ErasableGeneric, T: Sized + ErasableGeneric<Repr = Self::Repr>,

Perform a zero-cost type-safe upcast to a wider ref type within the Wasm bindgen generics type system. Read more
Source§

fn upcast_into(self) -> T
where Self: Sized + ErasableGeneric, T: Sized + ErasableGeneric<Repr = Self::Repr>,

Perform a zero-cost type-safe upcast to a wider type within the Wasm bindgen generics type system. Read more