1use std::cell::Cell;
4use std::fmt;
5use std::future::Future;
6use std::rc::Rc;
7use std::time::Duration;
8
9use reactive::{Effect, Signal, signal, untracked};
10
11use crate::task::{Task, spawn, spawn_local};
12use crate::timer::after;
13
14pub struct Resource<T: 'static, E: 'static = String> {
39 value: Signal<Option<T>>,
40 error: Signal<Option<E>>,
41 loading: Signal<bool>,
42 version: Signal<u64>,
43}
44
45pub fn resource<S, T, E, Fut>(source: impl Fn() -> S + 'static, fetcher: impl Fn(S) -> Fut + 'static) -> Resource<T, E>
47where
48 S: 'static,
49 T: Send + 'static,
50 E: Send + 'static,
51 Fut: Future<Output = Result<T, E>> + Send + 'static,
52{
53 build(source, fetcher, spawn)
54}
55
56#[cfg(feature = "tokio")]
66pub fn resource_tokio<S, T, E, Fut>(source: impl Fn() -> S + 'static, fetcher: impl Fn(S) -> Fut + 'static) -> Resource<T, E>
67where
68 S: 'static,
69 T: Send + 'static,
70 E: Send + 'static,
71 Fut: Future<Output = Result<T, E>> + Send + 'static,
72{
73 build(source, fetcher, crate::task::spawn_tokio)
74}
75
76fn build<S, T, E, Fut>(
78 source: impl Fn() -> S + 'static,
79 fetcher: impl Fn(S) -> Fut + 'static,
80 run: fn(Fut) -> Task<Result<T, E>>,
81) -> Resource<T, E>
82where
83 S: 'static,
84 T: Send + 'static,
85 E: Send + 'static,
86 Fut: Future<Output = Result<T, E>> + Send + 'static,
87{
88 let r = Resource { value: signal(None), error: signal(None), loading: signal(false), version: signal(0) };
89 let latest = Rc::new(Cell::new(0u64));
91 Effect::new(move || {
92 r.version.with(|_| ());
93 let input = source();
94 let future = untracked(|| fetcher(input));
95 let request = latest.get() + 1;
96 latest.set(request);
97 r.loading.set_if_changed(true);
98 let latest = latest.clone();
99 let task = run(future);
101 spawn_local(async move {
102 let result = task.result().await;
103 if latest.get() != request {
104 return;
105 }
106 match result {
107 Ok(Ok(value)) => {
108 r.value.set(Some(value));
109 if r.error.with_untracked(Option::is_some) {
110 r.error.set(None);
111 }
112 }
113 Ok(Err(error)) => r.error.set(Some(error)),
114 Err(_) => {}
115 }
116 r.loading.set(false);
117 });
118 });
119 r
120}
121
122impl<T: 'static, E: 'static> Resource<T, E> {
123 pub fn is_loading(&self) -> bool {
125 self.loading.get()
126 }
127
128 pub fn get(&self) -> Option<T>
130 where
131 T: Clone,
132 {
133 self.value.get()
134 }
135
136 pub fn with<R>(&self, f: impl FnOnce(Option<&T>) -> R) -> R {
138 self.value.with(|value| f(value.as_ref()))
139 }
140
141 pub fn error(&self) -> Option<E>
143 where
144 E: Clone,
145 {
146 self.error.get()
147 }
148
149 pub fn with_error<R>(&self, f: impl FnOnce(Option<&E>) -> R) -> R {
151 self.error.with(|error| f(error.as_ref()))
152 }
153
154 pub fn refetch(&self) {
156 self.version.update(|v| *v += 1);
157 }
158
159 pub fn set(&self, value: T) {
161 self.value.set(Some(value));
162 }
163}
164
165impl<T, E> Clone for Resource<T, E> {
166 fn clone(&self) -> Self {
167 *self
168 }
169}
170
171impl<T, E> Copy for Resource<T, E> {}
172
173impl<T, E> fmt::Debug for Resource<T, E> {
174 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
175 f.debug_struct("Resource").field("value", &self.value).field("loading", &self.loading).finish()
176 }
177}
178
179pub fn debounced<T: Clone + PartialEq + 'static>(source: impl Fn() -> T + 'static, delay: Duration) -> Signal<T> {
182 let output = signal(untracked(&source));
183 Effect::new(move || {
184 let value = source();
185 if !output.with_untracked(|current| *current == value) {
188 after(delay, move || {
189 output.set_if_changed(value);
190 });
191 }
192 });
193 output
194}