Skip to main content

mitsuami_core/
resource.rs

1//! Async state as signals: [`resource`] for loading data, [`action`] for
2//! running operations, each with its pending state.
3//!
4//! ```ignore
5//! let user = resource_on(move || user_id.get(), |id| async move { api::user(id).await });
6//! view! {
7//!     <Show when=move || user.loading()><Text>"Loading…"</Text></Show>
8//!     <Text>{move || user.with_data(|u| u.map(|u| u.name.clone()).unwrap_or_default())}</Text>
9//! }
10//!
11//! let save = action(|draft: Draft| async move { api::save(draft).await });
12//! view! { <Button enabled=move || !save.pending() @click=move || save.dispatch(draft())>"Save"</Button> }
13//! ```
14//!
15//! Both run their futures on the UI thread, owned by the scope that created
16//! them: disposing it (closing the window, hiding the component) cancels
17//! what's in flight. Put blocking work in `spawn_blocking`.
18
19use std::cell::{Cell, RefCell};
20use std::collections::HashMap;
21use std::future::Future;
22use std::pin::Pin;
23use std::rc::Rc;
24
25use mitsuami_reactive::{Owner, Signal, batch, effect, on_cleanup, signal, untrack};
26
27use crate::task::{TaskHandle, current_ui, spawn_local};
28
29/// Data loaded asynchronously: [`resource`] or [`resource_on`].
30///
31/// It fetches when created, again whenever its source changes, and on
32/// [`refetch`](Resource::refetch). A new fetch cancels the one in flight.
33/// While it loads, the previous data stays available; an error keeps it
34/// too, so a view can show both.
35pub struct Resource<T: 'static, E: 'static> {
36    data: Signal<Option<T>>,
37    error: Signal<Option<E>>,
38    loading: Signal<bool>,
39    refetches: Signal<u64>,
40}
41
42impl<T: 'static, E: 'static> Clone for Resource<T, E> {
43    fn clone(&self) -> Self {
44        *self
45    }
46}
47
48impl<T: 'static, E: 'static> Copy for Resource<T, E> {}
49
50/// Loads `fetch()` now; again on [`Resource::refetch`].
51pub fn resource<T, E, Fut>(fetch: impl Fn() -> Fut + 'static) -> Resource<T, E>
52where
53    Fut: Future<Output = Result<T, E>> + 'static,
54{
55    resource_on(|| (), move |()| fetch())
56}
57
58/// Loads `fetch(source())` now, and again whenever the signals `source`
59/// reads change. Vue's `watch` plus a fetch; the future's own reads aren't
60/// tracked.
61pub fn resource_on<S, T, E, Fut>(source: impl Fn() -> S + 'static, fetch: impl Fn(S) -> Fut + 'static) -> Resource<T, E>
62where
63    S: 'static,
64    Fut: Future<Output = Result<T, E>> + 'static,
65{
66    let resource = Resource { data: signal(None), error: signal(None), loading: signal(false), refetches: signal(0) };
67    let Resource { data, error, loading, refetches } = resource;
68    effect(move || {
69        refetches.with(|_| ());
70        let source = source();
71        untrack(|| {
72            if !loading.get_untracked() {
73                loading.set(true);
74            }
75            let future = fetch(source);
76            // Owned by this run of the effect: the next run cancels it.
77            spawn_local(async move {
78                let result = future.await;
79                batch(|| {
80                    match result {
81                        Ok(value) => {
82                            data.set(Some(value));
83                            if error.with_untracked(Option::is_some) {
84                                error.set(None);
85                            }
86                        }
87                        Err(e) => error.set(Some(e)),
88                    }
89                    loading.set(false);
90                });
91            });
92        });
93    });
94    resource
95}
96
97impl<T: 'static, E: 'static> Resource<T, E> {
98    /// Whether a fetch is in flight.
99    pub fn loading(&self) -> bool {
100        self.loading.get()
101    }
102
103    /// The last data loaded, if any.
104    pub fn data(&self) -> Option<T>
105    where
106        T: Clone,
107    {
108        self.data.get()
109    }
110
111    /// Borrows the last data loaded.
112    pub fn with_data<R>(&self, f: impl FnOnce(Option<&T>) -> R) -> R {
113        self.data.with(|data| f(data.as_ref()))
114    }
115
116    /// The error of the last fetch, if it failed.
117    pub fn error(&self) -> Option<E>
118    where
119        E: Clone,
120    {
121        self.error.get()
122    }
123
124    /// Borrows the error of the last fetch, if it failed.
125    pub fn with_error<R>(&self, f: impl FnOnce(Option<&E>) -> R) -> R {
126        self.error.with(|error| f(error.as_ref()))
127    }
128
129    /// Fetches again with the current source.
130    pub fn refetch(&self) {
131        self.refetches.update(|n| *n += 1);
132    }
133
134    /// Replaces the data locally, e.g. optimistically after a change the
135    /// server will confirm on the next fetch.
136    pub fn set_data(&self, value: T) {
137        self.data.set(Some(value));
138    }
139}
140
141type RunFn<I, O> = Rc<dyn Fn(I) -> Pin<Box<dyn Future<Output = O>>>>;
142
143struct ActionState<I, O> {
144    run: RunFn<I, O>,
145    owner: Option<Owner>,
146    /// In flight, by dispatch number; cancelled with the owner.
147    tasks: RefCell<HashMap<u64, TaskHandle>>,
148    dispatches: Cell<u64>,
149}
150
151/// An async operation and its state: [`action`].
152pub struct Action<I: 'static, O: 'static> {
153    state: Signal<Rc<ActionState<I, O>>>,
154    pending: Signal<usize>,
155    value: Signal<Option<O>>,
156}
157
158impl<I: 'static, O: 'static> Clone for Action<I, O> {
159    fn clone(&self) -> Self {
160        *self
161    }
162}
163
164impl<I: 'static, O: 'static> Copy for Action<I, O> {}
165
166/// Wraps `run` so each [`dispatch`](Action::dispatch) runs it as a task,
167/// tracking whether any is [`pending`](Action::pending) and keeping the
168/// [`value`](Action::value) of the latest one.
169pub fn action<I, O, Fut>(run: impl Fn(I) -> Fut + 'static) -> Action<I, O>
170where
171    Fut: Future<Output = O> + 'static,
172{
173    let state = Rc::new(ActionState {
174        run: Rc::new(move |input| Box::pin(run(input)) as Pin<Box<dyn Future<Output = O>>>),
175        owner: Owner::current(),
176        tasks: RefCell::default(),
177        dispatches: Cell::new(0),
178    });
179    let in_flight = state.clone();
180    on_cleanup(move || {
181        for (_, task) in in_flight.tasks.take() {
182            task.cancel();
183        }
184    });
185    Action { state: signal(state), pending: signal(0), value: signal(None) }
186}
187
188impl<I: 'static, O: 'static> Action<I, O> {
189    /// Runs the action with `input`. Dispatches may overlap; the value is
190    /// the result of the latest one.
191    pub fn dispatch(&self, input: I) {
192        let state = self.state.get_untracked();
193        let future = (state.run)(input);
194        let number = state.dispatches.get() + 1;
195        state.dispatches.set(number);
196        let Action { pending, value, .. } = *self;
197        pending.update(|n| *n += 1);
198        let finished = state.clone();
199        let task = current_ui().spawn_in(
200            async move {
201                let output = future.await;
202                finished.tasks.borrow_mut().remove(&number);
203                batch(|| {
204                    pending.update(|n| *n -= 1);
205                    if finished.dispatches.get() == number {
206                        value.set(Some(output));
207                    }
208                });
209            },
210            state.owner,
211        );
212        state.tasks.borrow_mut().insert(number, task);
213    }
214
215    /// Whether any dispatch is still running.
216    pub fn pending(&self) -> bool {
217        self.pending.get() > 0
218    }
219
220    /// The result of the latest dispatch, once it finished.
221    pub fn value(&self) -> Option<O>
222    where
223        O: Clone,
224    {
225        self.value.get()
226    }
227
228    /// Borrows the result of the latest dispatch.
229    pub fn with_value<R>(&self, f: impl FnOnce(Option<&O>) -> R) -> R {
230        self.value.with(|value| f(value.as_ref()))
231    }
232}