Skip to main content

Memo

Struct Memo 

Source
pub struct Memo<T, S = SyncStorage>
where S: Storage<T>,
{ /* private fields */ }
Expand description

A memo is an efficient derived reactive value based on other reactive values.

Unlike a “derived signal,” a memo comes with two guarantees:

  1. The memo will only run once per change, no matter how many times you access its value.
  2. The memo will only notify its dependents if the value of the computation changes.

This makes a memo the perfect tool for expensive computations.

Memos have a certain overhead compared to derived signals. In most cases, you should create a derived signal. But if the derivation calculation is expensive, you should create a memo.

Memos are lazy: they do not run at all until they are read for the first time, and they will not re-run the calculation when a source signal changes until they are read again.

This is an arena-allocated type, which is Copy and is disposed when its reactive Owner cleans up. For a reference-counted signal that lives as as long as a reference to it is alive, see ArcMemo.

let (value, set_value) = signal(0);

// 🆗 we could create a derived signal with a simple function
let double_value = move || value.get() * 2;
set_value.set(2);
assert_eq!(double_value(), 4);

// but imagine the computation is really expensive
let expensive = move || really_expensive_computation(value.get()); // lazy: doesn't run until called
Effect::new(move |_| {
  // 🆗 run #1: calls `really_expensive_computation` the first time
  println!("expensive = {}", expensive());
});
Effect::new(move |_| {
  // ❌ run #2: this calls `really_expensive_computation` a second time!
  let value = expensive();
  // do something else...
});

// instead, we create a memo
// 🆗 run #1: the calculation runs once immediately
let memoized = Memo::new(move |_| really_expensive_computation(value.get()));
Effect::new(move |_| {
  // 🆗 reads the current value of the memo
  //    can be `memoized()` on nightly
  println!("memoized = {}", memoized.get());
});
Effect::new(move |_| {
  // ✅ reads the current value **without re-running the calculation**
  let value = memoized.get();
  // do something else...
});

§Core Trait Implementations

  • .get() clones the current value of the memo. If you call it within an effect, it will cause that effect to subscribe to the memo, and to re-run whenever the value of the memo changes.
  • .read() returns a guard that allows accessing the value of the memo by reference. If you call it within an effect, it will cause that effect to subscribe to the memo, and to re-run whenever the value of the memo changes.
    • .read_untracked() gives access to the current value of the memo without reactively tracking it.
  • .with() allows you to reactively access the memo’s value without cloning by applying a callback function.
    • .with_untracked() allows you to access the memo’s value by applying a callback function without reactively tracking it.
  • .to_stream() converts the memo to an async stream of values.
  • ::from_stream() converts an async stream of values into a memo containing the latest value.

Implementations§

Source§

impl<T> Memo<T>
where T: Send + Sync + 'static,

Source

pub fn new(fun: impl Fn(Option<&T>) -> T + Send + Sync + 'static) -> Memo<T>
where T: PartialEq,

Creates a new memoized, computed reactive value.

As with an Effect, the argument to the memo function is the previous value, i.e., the current value of the memo, which will be None for the initial calculation.

let (value, set_value) = signal(0);

// the memo will reactively update whenever `value` changes
let memoized =
    Memo::new(move |_| really_expensive_computation(value.get()));
Source

pub fn new_with_compare( fun: impl Fn(Option<&T>) -> T + Send + Sync + 'static, changed: fn(Option<&T>, Option<&T>) -> bool, ) -> Memo<T>

Creates a new memo with a custom comparison function. By default, memos simply use PartialEq to compare the previous value to the new value. Passing a custom comparator allows you to compare the old and new values using any criteria.

changed should be a function that returns true if the new value is different from the old value.

Source

pub fn new_owning( fun: impl Fn(Option<T>) -> (T, bool) + Send + Sync + 'static, ) -> Memo<T>

Creates a new memo by passing a function that computes the value.

Unlike Memo::new, this receives ownership of the previous value. As a result, it must return both the new value and a bool that is true if the value has changed.

This is lazy: the function will not be called until the memo’s value is read for the first time.

Trait Implementations§

Source§

impl<T, S> Clone for Memo<T, S>
where S: Storage<T>,

Source§

fn clone(&self) -> Memo<T, S>

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, S> Copy for Memo<T, S>
where S: Storage<T>,

Source§

impl<T, S> Debug for Memo<T, S>
where S: Debug + Storage<T>,

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
Source§

impl<T, S> DefinedAt for Memo<T, S>
where S: Storage<T>,

Source§

fn defined_at(&self) -> Option<&'static Location<'static>>

Returns the location at which the signal was defined. This is usually simply None in release mode.
Source§

impl<T, S> Dispose for Memo<T, S>
where S: Storage<T>,

Source§

fn dispose(self)

Disposes of the signal. This: Read more
Source§

impl<T, S> Eq for Memo<T, S>
where S: Storage<T>,

Source§

impl<T> From<ArcMemo<T>> for Memo<T>
where T: Send + Sync + 'static,

Source§

fn from(value: ArcMemo<T>) -> Memo<T>

Converts to this type from the input type.
Source§

impl<T> From<ArcReadSignal<T>> for Memo<T>
where T: Clone + PartialEq + Send + Sync + 'static,

Source§

fn from(value: ArcReadSignal<T>) -> Memo<T>

Converts to this type from the input type.
Source§

impl<T> FromLocal<ArcMemo<T, LocalStorage>> for Memo<T, LocalStorage>
where T: 'static,

Source§

fn from_local(value: ArcMemo<T, LocalStorage>) -> Memo<T, LocalStorage>

Converts between the types.
Source§

impl<T, S> Hash for Memo<T, S>
where S: Storage<T>,

Source§

fn hash<H>(&self, state: &mut H)
where H: Hasher,

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl<T, S> PartialEq for Memo<T, S>
where S: Storage<T>,

Source§

fn eq(&self, other: &Memo<T, S>) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl<T, S> ReadUntracked for Memo<T, S>
where T: 'static, S: Storage<ArcMemo<T, S>> + Storage<T>,

Source§

type Value = ReadGuard<T, Mapped<Plain<Option<<S as Storage<T>>::Wrapped>>, T>>

The guard type that will be returned, which can be dereferenced to the value.
Source§

fn try_read_untracked(&self) -> Option<<Memo<T, S> as ReadUntracked>::Value>

Returns the guard, or None if the signal has already been disposed.
Source§

fn read_untracked(&self) -> Self::Value

Returns the guard. Read more
Source§

fn custom_try_read(&self) -> Option<Option<Self::Value>>

This is a backdoor to allow overriding the Read::try_read implementation despite it being auto implemented. Read more
Source§

impl<T, S> Track for Memo<T, S>
where T: 'static, S: Storage<ArcMemo<T, S>> + Storage<T>, ArcMemo<T, S>: Track,

Source§

fn track(&self)

Subscribes to this signal in the current reactive scope without doing anything with its value.

Auto Trait Implementations§

§

impl<T, S> Freeze for Memo<T, S>
where ArenaItem<ArcMemo<T, S>, S>: Freeze,

§

impl<T, S> RefUnwindSafe for Memo<T, S>
where ArenaItem<ArcMemo<T, S>, S>: RefUnwindSafe,

§

impl<T, S> Send for Memo<T, S>
where ArenaItem<ArcMemo<T, S>, S>: Send,

§

impl<T, S> Sync for Memo<T, S>
where ArenaItem<ArcMemo<T, S>, S>: Sync,

§

impl<T, S> Unpin for Memo<T, S>
where ArenaItem<ArcMemo<T, S>, S>: Unpin,

§

impl<T, S> UnsafeUnpin for Memo<T, S>
where ArenaItem<ArcMemo<T, S>, S>: UnsafeUnpin,

§

impl<T, S> UnwindSafe for Memo<T, S>
where ArenaItem<ArcMemo<T, S>, S>: UnwindSafe,

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<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

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> Downcast for T
where T: Any,

Source§

fn into_any(self: Box<T>) -> Box<dyn Any>

Convert Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>. Box<dyn Any> can then be further downcast into Box<ConcreteType> where ConcreteType implements Trait.
Source§

fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>

Convert Rc<Trait> (where Trait: Downcast) to Rc<Any>. Rc<Any> can then be further downcast into Rc<ConcreteType> where ConcreteType implements Trait.
Source§

fn as_any(&self) -> &(dyn Any + 'static)

Convert &Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &Any’s vtable from &Trait’s.
Source§

fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)

Convert &mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &mut Any’s vtable from &mut Trait’s.
Source§

impl<T> DowncastSync for T
where T: Any + Send + Sync,

Source§

fn into_any_arc(self: Arc<T>) -> Arc<dyn Any + Sync + Send> ⓘ

Convert Arc<Trait> (where Trait: Downcast) to Arc<Any>. Arc<Any> can then be further downcast into Arc<ConcreteType> where ConcreteType implements Trait.
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Checks if this value is equivalent to the given key. Read more
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Compare self to key and return true if they are equal.
Source§

impl<T> ErasedDestructor for T
where T: 'static,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<S, T> FromStream<T> for S
where S: From<ArcReadSignal<Option<T>>> + Send + Sync, T: Send + Sync + 'static,

Source§

fn from_stream(stream: impl Stream<Item = T> + Send + 'static) -> S

Creates a signal that contains the latest value of the stream.
Source§

fn from_stream_unsync(stream: impl Stream<Item = T> + 'static) -> S

Creates a signal that contains the latest value of the stream.
Source§

impl<T> Get for T
where T: With, <T as With>::Value: Clone,

Source§

type Value = <T as With>::Value

The type of the value contained in the signal.
Source§

fn try_get(&self) -> Option<<T as Get>::Value>

Subscribes to the signal, then clones and returns the value of the signal, or None if the signal has already been disposed.
Source§

fn get(&self) -> Self::Value

Subscribes to the signal, then clones and returns the value of the signal. Read more
Source§

impl<T> GetUntracked for T

Source§

type Value = <T as WithUntracked>::Value

The type of the value contained in the signal.
Source§

fn try_get_untracked(&self) -> Option<<T as GetUntracked>::Value>

Clones and returns the value of the signal, or None if the signal has already been disposed.
Source§

fn get_untracked(&self) -> Self::Value

Clones and returns the value of the signal, Read more
Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
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> Read for T
where T: Track + ReadUntracked,

Source§

type Value = <T as ReadUntracked>::Value

The guard type that will be returned, which can be dereferenced to the value.
Source§

fn try_read(&self) -> Option<<T as Read>::Value>

Subscribes to the signal, and returns the guard, or None if the signal has already been disposed.
Source§

fn read(&self) -> Self::Value

Subscribes to the signal, and returns the guard. Read more
Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T, S> SimdFrom<T, S> for T
where S: Simd,

Source§

fn simd_from(_simd: S, value: T) -> T

Source§

impl<F, T, S> SimdInto<T, S> for F
where T: SimdFrom<F, S>, S: Simd,

Source§

fn simd_into(self, simd: S) -> T

Source§

impl<T> StorageAccess<T> for T

Source§

fn as_borrowed(&self) -> &T

Borrows the value.
Source§

fn into_taken(self) -> T

Takes the value.
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<S> ToStream<<S as Get>::Value> for S
where S: Clone + Get + Send + Sync + 'static, <S as Get>::Value: Send + 'static,

Source§

fn to_stream(&self) -> impl Stream<Item = <S as Get>::Value> + Send

Generates a Stream that emits the new value of the signal whenever it changes. 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<T> WasmNotSend for T
where T: Send,

Source§

impl<T> WasmNotSendSync for T

Source§

impl<T> WasmNotSync for T
where T: Sync,

Source§

impl<T> With for T
where T: Read,

Source§

type Value = <<T as Read>::Value as Deref>::Target

The type of the value contained in the signal.
Source§

fn try_with<U>(&self, fun: impl FnOnce(&<T as With>::Value) -> U) -> Option<U>

Subscribes to the signal, applies the closure to the value, and returns the result, or None if the signal has already been disposed.
Source§

fn with<U>(&self, fun: impl FnOnce(&Self::Value) -> U) -> U

Subscribes to the signal, applies the closure to the value, and returns the result. Read more
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> WithUntracked for T

Source§

type Value = <<T as ReadUntracked>::Value as Deref>::Target

The type of the value contained in the signal.
Source§

fn try_with_untracked<U>( &self, fun: impl FnOnce(&<T as WithUntracked>::Value) -> U, ) -> Option<U>

Applies the closure to the value, and returns the result, or None if the signal has already been disposed.
Source§

fn with_untracked<U>(&self, fun: impl FnOnce(&Self::Value) -> U) -> U

Applies the closure to the value, and returns the result. Read more