Struct leptos::Resource

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

A signal that reflects the current state of an asynchronous task, allowing you to integrate async Futures into the synchronous reactive system.

Takes a fetcher function that generates a Future when called and a source signal that provides the argument for the fetcher. Whenever the value of the source changes, a new Future will be created and run.

When server-side rendering is used, the server will handle running the Future and will stream the result to the client. This process requires the output type of the Future to be Serializable. If your output cannot be serialized, or you just want to make sure the Future runs locally, use create_local_resource().

// any old async function; maybe this is calling a REST API or something
async fn fetch_cat_picture_urls(how_many: i32) -> Vec<String> {
  // pretend we're fetching cat pics
  vec![how_many.to_string()]
}

// a signal that controls how many cat pics we want
let (how_many_cats, set_how_many_cats) = create_signal(1);

// create a resource that will refetch whenever `how_many_cats` changes
let cats = create_resource(move || how_many_cats.get(), fetch_cat_picture_urls);

// when we read the signal, it contains either
// 1) None (if the Future isn't ready yet) or
// 2) Some(T) (if the future's already resolved)
assert_eq!(cats.get(), Some(vec!["1".to_string()]));

// when the signal's value changes, the `Resource` will generate and run a new `Future`
set_how_many_cats.set(2);
assert_eq!(cats.get(), Some(vec!["2".to_string()]));

We can provide single, multiple or even a non-reactive signal as source

// Single signal. `Resource` will run once initially and then every time `how_many_cats` changes
let async_data = create_resource(move || how_many_cats.get() , |_| async move { todo!() });
// Non-reactive signal. `Resource` runs only once
let async_data = create_resource(|| (), |_| async move { todo!() });
// Multiple signals. `Resource` will run once initially and then every time `how_many_cats` or `how_many_dogs` changes
let async_data = create_resource(move || (how_many_cats.get(), how_many_dogs.get()), |_| async move { todo!() });

Implementations§

source§

impl<S, T> Resource<S, T>
where S: Clone + 'static, T: 'static,

source

pub fn read(&self) -> Option<T>
where T: Clone,

👎Deprecated: You can now use .get() on resources.

Clones and returns the current value of the resource (Option::None if the resource is still pending). Also subscribes the running effect to this resource.

If you want to get the value without cloning it, use Resource::with. (value.read() is equivalent to value.with(T::clone).)

source

pub fn map<U>(&self, f: impl FnOnce(&T) -> U) -> Option<U>

Applies a function to the current value of the resource, and subscribes the running effect to this resource. If the resource hasn’t yet resolved, the function won’t be called and this will return Option::None.

If you want to get the value by cloning it, you can use Resource::read.

source

pub fn loading(&self) -> Signal<bool>

Returns a signal that indicates whether the resource is currently loading.

source

pub fn refetch(&self)

Re-runs the async function with the current source data.

source§

impl<S, T, E> Resource<S, Result<T, E>>
where E: Clone, S: Clone,

source

pub fn and_then<U>(&self, f: impl FnOnce(&T) -> U) -> Option<Result<U, E>>

Applies the given function when a resource that returns Result<T, E> has resolved and loaded an Ok(_), rather than requiring nested .map() calls over the Option<Result<_, _>> returned by the resource.

This is useful when used with features like server functions, in conjunction with <ErrorBoundary/> and <Suspense/>, when these other components are left to handle the None and Err(_) states.

let cats = create_resource(
    || (),
    |_| async { Ok(vec![0, 1, 2]) as Result<Vec<i32>, ()> },
);
create_effect(move |_| {
    cats.and_then(|data: &Vec<i32>| println!("{}", data.len()));
});
source§

impl<S, T> Resource<S, T>
where S: 'static, T: 'static,

source

pub fn new<Fu>( source: impl Fn() -> S + 'static, fetcher: impl Fn(S) -> Fu + 'static, ) -> Resource<S, T>
where S: PartialEq + Clone + 'static, T: Serializable + 'static, Fu: Future<Output = T> + 'static,

Creates a Resource, which is a signal that reflects the current state of an asynchronous task, allowing you to integrate async Futures into the synchronous reactive system.

Takes a fetcher function that generates a Future when called and a source signal that provides the argument for the fetcher. Whenever the value of the source changes, a new Future will be created and run.

When server-side rendering is used, the server will handle running the Future and will stream the result to the client. This process requires the output type of the Future to be Serializable. If your output cannot be serialized, or you just want to make sure the Future runs locally, use create_local_resource().

This is identical with create_resource.

// any old async function; maybe this is calling a REST API or something
async fn fetch_cat_picture_urls(how_many: i32) -> Vec<String> {
  // pretend we're fetching cat pics
  vec![how_many.to_string()]
}

// a signal that controls how many cat pics we want
let (how_many_cats, set_how_many_cats) = create_signal(1);

// create a resource that will refetch whenever `how_many_cats` changes
let cats = Resource::new(move || how_many_cats.get(), fetch_cat_picture_urls);

// when we read the signal, it contains either
// 1) None (if the Future isn't ready yet) or
// 2) Some(T) (if the future's already resolved)
assert_eq!(cats.get(), Some(vec!["1".to_string()]));

// when the signal's value changes, the `Resource` will generate and run a new `Future`
set_how_many_cats.set(2);
assert_eq!(cats.get(), Some(vec!["2".to_string()]));
source

pub fn local<Fu>( source: impl Fn() -> S + 'static, fetcher: impl Fn(S) -> Fu + 'static, ) -> Resource<S, T>
where S: PartialEq + Clone + 'static, T: 'static, Fu: Future<Output = T> + 'static,

Creates a local Resource, which is a signal that reflects the current state of an asynchronous task, allowing you to integrate async Futures into the synchronous reactive system.

Takes a fetcher function that generates a Future when called and a source signal that provides the argument for the fetcher. Whenever the value of the source changes, a new Future will be created and run.

Unlike create_resource(), this Future is always run on the local system and therefore it’s result type does not need to be Serializable.

This is identical with create_local_resource.

#[derive(Debug, Clone)] // doesn't implement Serialize, Deserialize
struct ComplicatedUnserializableStruct {
    // something here that can't be serialized
}
// any old async function; maybe this is calling a REST API or something
async fn setup_complicated_struct() -> ComplicatedUnserializableStruct {
    // do some work
    ComplicatedUnserializableStruct {}
}

// create the resource; it will run but not be serialized
let result =
    create_local_resource(move || (), |_| setup_complicated_struct());
source§

impl<T> Resource<(), T>
where T: 'static,

source

pub fn once<Fu>(fetcher: impl Fn() -> Fu + 'static) -> Resource<(), T>
where T: Serializable + 'static, Fu: Future<Output = T> + 'static,

Creates a resource that will only load once, and will not respond to any reactive changes, including changes in any reactive variables read in its fetcher.

This identical to create_resource(|| (), move |_| fetcher()).

Trait Implementations§

source§

impl<S, T> Clone for Resource<S, T>
where S: 'static, T: 'static,

source§

fn clone(&self) -> Resource<S, 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<S, T> Debug for Resource<S, T>
where S: Debug + 'static, T: Debug + 'static,

source§

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

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

impl<S, T> Hash for Resource<S, T>
where S: Hash + 'static, T: Hash + 'static,

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<S, T> IntoView for Resource<S, T>
where S: Clone, T: IntoView + Clone,

source§

fn into_view(self) -> View

Converts the value into View.
source§

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

source§

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

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

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

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

impl<S, T> SignalDispose for Resource<S, T>
where S: 'static, T: 'static,

source§

fn dispose(self)

Disposes of the signal. This: Read more
source§

impl<S, T> SignalGet for Resource<S, T>
where S: Clone, T: Clone,

source§

type Value = Option<T>

The value held by the signal.
source§

fn get(&self) -> Option<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<Option<T>>

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

impl<S, T> SignalSet for Resource<S, T>

source§

type Value = T

The value held by the signal.
source§

fn set(&self, new_value: T)

Sets the signal’s value and notifies subscribers. Read more
source§

fn try_set(&self, new_value: T) -> Option<T>

Sets the signal’s value and notifies subscribers. Returns None if the signal is still valid, [Some(T)] otherwise. Read more
source§

impl<S, T> SignalUpdate for Resource<S, T>

source§

type Value = Option<T>

The value held by the signal.
source§

fn update(&self, f: impl FnOnce(&mut Option<T>))

Applies a function to the current value to mutate it in place and notifies subscribers that the signal has changed. Read more
source§

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

Applies a function to the current value to mutate it in place and notifies subscribers that the signal has changed. Returns [Some(O)] if the signal is still valid, None otherwise. Read more
source§

impl<S, T> SignalWith for Resource<S, T>
where S: Clone,

source§

type Value = Option<T>

The value held by the signal.
source§

fn with<O>(&self, f: impl FnOnce(&Option<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(&Option<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<S, T> Copy for Resource<S, T>
where S: 'static, T: 'static,

source§

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

source§

impl<S, T> StructuralPartialEq for Resource<S, T>
where S: 'static, T: 'static,

Auto Trait Implementations§

§

impl<S, T> Freeze for Resource<S, T>

§

impl<S, T> RefUnwindSafe for Resource<S, T>

§

impl<S, T> Send for Resource<S, T>
where S: Send, T: Send,

§

impl<S, T> Sync for Resource<S, T>
where S: Sync, T: Sync,

§

impl<S, T> Unpin for Resource<S, T>
where S: Unpin, T: Unpin,

§

impl<S, T> UnwindSafe for Resource<S, T>
where S: UnwindSafe, T: 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<T> CloneToUninit for T
where T: Clone,

source§

unsafe fn clone_to_uninit(&self, dst: *mut T)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. 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

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> 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 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> IntoEither for T

source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
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 = 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 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> 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 El
where El: Debug,