mitsuami_core/
resource.rs1use 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
29pub 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
50pub 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
58pub 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 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 pub fn loading(&self) -> bool {
100 self.loading.get()
101 }
102
103 pub fn data(&self) -> Option<T>
105 where
106 T: Clone,
107 {
108 self.data.get()
109 }
110
111 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 pub fn error(&self) -> Option<E>
118 where
119 E: Clone,
120 {
121 self.error.get()
122 }
123
124 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 pub fn refetch(&self) {
131 self.refetches.update(|n| *n += 1);
132 }
133
134 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 tasks: RefCell<HashMap<u64, TaskHandle>>,
148 dispatches: Cell<u64>,
149}
150
151pub 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
166pub 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 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 pub fn pending(&self) -> bool {
217 self.pending.get() > 0
218 }
219
220 pub fn value(&self) -> Option<O>
222 where
223 O: Clone,
224 {
225 self.value.get()
226 }
227
228 pub fn with_value<R>(&self, f: impl FnOnce(Option<&O>) -> R) -> R {
230 self.value.with(|value| f(value.as_ref()))
231 }
232}