Struct leptos::Memo

source ·
pub struct Memo<T>where
    T: 'static,{ /* private fields */ }
Expand description

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.

As with create_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.

Core Trait Implementations

  • .get() (or calling the signal as a function) clones the current value of the signal. If you call it within an effect, it will cause that effect to subscribe to the signal, and to re-run whenever the value of the signal changes.
    • .get_untracked() clones the value of the signal without reactively tracking it.
  • .with() allows you to reactively access the signal’s value without cloning by applying a callback function.
    • .with_untracked() allows you to access the signal’s value without reactively tracking it.
  • .to_stream() converts the signal to an async stream of values.

Examples

let (value, set_value) = create_signal(cx, 0);

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

// but imagine the computation is really expensive
let expensive = move || really_expensive_computation(value()); // lazy: doesn't run until called
create_effect(cx, move |_| {
  // 🆗 run #1: calls `really_expensive_computation` the first time
  log::debug!("expensive = {}", expensive());
});
create_effect(cx, 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 = create_memo(cx, move |_| really_expensive_computation(value()));
create_effect(cx, move |_| {
 // 🆗 reads the current value of the memo
  log::debug!("memoized = {}", memoized());
});
create_effect(cx, move |_| {
  // ✅ reads the current value **without re-running the calculation**
  let value = memoized();
  // do something else...
});

Trait Implementations§

source§

impl<T> Clone for Memo<T>where T: 'static,

source§

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

Returns a copy of the value. Read more
1.0.0 · source§

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

Performs copy-assignment from source. Read more
source§

impl<T> Debug for Memo<T>where T: Debug + 'static,

source§

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

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

impl<T> From<Memo<T>> for MaybeSignal<T>

source§

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

Converts to this type from the input type.
source§

impl<T> From<Memo<T>> for Signal<T>

source§

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

Converts to this type from the input type.
source§

impl<T> IntoView for Memo<T>where T: IntoView + Clone,

source§

fn into_view(self, cx: Scope) -> View

Converts the value into View.
source§

impl<T> PartialEq<Memo<T>> for Memo<T>where T: PartialEq<T> + 'static,

source§

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

This method tests for self and other values to be equal, and is used by ==.
1.0.0 · source§

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

This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
source§

impl<T> SignalDispose for Memo<T>

source§

fn dispose(self)

Disposes of the signal. This: Read more
source§

impl<T> SignalGet<T> for Memo<T>where T: Clone,

Examples

let (count, set_count) = create_signal(cx, 0);
let double_count = create_memo(cx, move |_| count() * 2);

assert_eq!(double_count.get(), 0);
set_count(1);

// double_count() is shorthand for double_count.get()
assert_eq!(double_count(), 2);
source§

fn get(&self) -> T

Clones and returns the current value of the signal, and subscribes the running effect to this signal. Read more
source§

fn try_get(&self) -> Option<T>

Clones and returns the signal value, returning Some if the signal is still alive, and None otherwise.
source§

impl<T> SignalGetUntracked<T> for Memo<T>where T: Clone,

source§

fn get_untracked(&self) -> T

Gets the signal’s value without creating a dependency on the current scope. Read more
source§

fn try_get_untracked(&self) -> Option<T>

Gets the signal’s value without creating a dependency on the current scope. Returns [Some(T)] if the signal is still valid, None otherwise.
source§

impl<T> SignalStream<T> for Memo<T>where T: Clone,

source§

fn to_stream( &self, cx: Scope ) -> Pin<Box<dyn Stream<Item = T> + 'static, Global>>

Generates a Stream that emits the new value of the signal whenever it changes. Read more
source§

impl<T> SignalWith<T> for Memo<T>

source§

fn with<O>(&self, f: impl FnOnce(&T) -> O) -> O

Applies a function to the current value of the signal, and subscribes the running effect to this signal. Read more
source§

fn try_with<O>(&self, f: impl FnOnce(&T) -> O) -> Option<O>

Applies a function to the current value of the signal, and subscribes the running effect to this signal. Returns Some if the signal is valid and the function ran, otherwise returns None.
source§

fn track(&self)

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

impl<T> SignalWithUntracked<T> for Memo<T>

source§

fn with_untracked<O>(&self, f: impl FnOnce(&T) -> O) -> O

Runs the provided closure with a reference to the current value without creating a dependency on the current scope. Read more
source§

fn try_with_untracked<O>(&self, f: impl FnOnce(&T) -> O) -> Option<O>

Runs the provided closure with a reference to the current value without creating a dependency on the current scope. Returns [Some(O)] if the signal is still valid, None otherwise.
source§

impl<T> Copy for Memo<T>

source§

impl<T> Eq for Memo<T>where T: Eq + 'static,

source§

impl<T> StructuralEq for Memo<T>where T: 'static,

source§

impl<T> StructuralPartialEq for Memo<T>where T: 'static,

Auto Trait Implementations§

§

impl<T> RefUnwindSafe for Memo<T>where T: RefUnwindSafe,

§

impl<T> Send for Memo<T>where T: Send,

§

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

§

impl<T> Unpin for Memo<T>where T: Unpin,

§

impl<T> UnwindSafe for Memo<T>where T: UnwindSafe,

Blanket Implementations§

source§

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

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

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

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

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

source§

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

Mutably borrows from an owned value. Read more
source§

impl<Q, K> Equivalent<K> for Qwhere 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> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

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 Twhere 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 Twhere T: Clone,

§

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 Twhere U: Into<T>,

§

type Error = Infallible

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

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

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

§

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> 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<El> ElementDescriptorBounds for Elwhere El: Debug,