1
0

use_resource.rs 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. #![allow(missing_docs)]
  2. use crate::{dependency, use_callback, use_signal, UseCallback};
  3. use dioxus_core::prelude::*;
  4. use dioxus_core::{
  5. prelude::{spawn, use_hook},
  6. Task,
  7. };
  8. use dioxus_signals::*;
  9. use futures_util::{future, pin_mut, FutureExt, StreamExt};
  10. use std::ops::Deref;
  11. use std::{cell::Cell, future::Future, rc::Rc};
  12. /// A memo that resolves to a value asynchronously.
  13. /// Similar to `use_future` but `use_resource` returns a value.
  14. /// See [`Resource`] for more details.
  15. /// ```rust
  16. ///fn app() -> Element {
  17. /// let country = use_signal(|| WeatherLocation {
  18. /// city: "Berlin".to_string(),
  19. /// country: "Germany".to_string(),
  20. /// coordinates: (52.5244, 13.4105)
  21. /// });
  22. ///
  23. /// // Because the resource's future subscribes to `country` by reading it (`country.read()`),
  24. /// // everytime `country` changes the resource's future will run again and thus provide a new value.
  25. /// let current_weather = use_resource(move || async move { get_weather(&country.read().clone()).await });
  26. ///
  27. /// rsx! {
  28. /// // the value of the resource can be polled to
  29. /// // conditionally render elements based off if it's future
  30. /// // finished (Some(Ok(_)), errored Some(Err(_)),
  31. /// // or is still running (None)
  32. /// match current_weather.value() {
  33. /// Some(Ok(weather)) => WeatherElement { weather },
  34. /// Some(Err(e)) => p { "Loading weather failed, {e}" }
  35. /// None => p { "Loading..." }
  36. /// }
  37. /// }
  38. ///}
  39. /// ```
  40. #[must_use = "Consider using `cx.spawn` to run a future without reading its value"]
  41. pub fn use_resource<T, F>(future: impl Fn() -> F + 'static) -> Resource<T>
  42. where
  43. T: 'static,
  44. F: Future<Output = T> + 'static,
  45. {
  46. let mut value = use_signal(|| None);
  47. let mut state = use_signal(|| UseResourceState::Pending);
  48. let (rc, changed) = use_hook(|| {
  49. let (rc, changed) = ReactiveContext::new();
  50. (rc, Rc::new(Cell::new(Some(changed))))
  51. });
  52. let cb = use_callback(move || {
  53. // Create the user's task
  54. #[allow(clippy::redundant_closure)]
  55. let fut = rc.run_in(|| future());
  56. // Spawn a wrapper task that polls the innner future and watch its dependencies
  57. spawn(async move {
  58. // move the future here and pin it so we can poll it
  59. let fut = fut;
  60. pin_mut!(fut);
  61. // Run each poll in the context of the reactive scope
  62. // This ensures the scope is properly subscribed to the future's dependencies
  63. let res = future::poll_fn(|cx| rc.run_in(|| fut.poll_unpin(cx))).await;
  64. // Set the value and state
  65. state.set(UseResourceState::Ready);
  66. value.set(Some(res));
  67. })
  68. });
  69. let mut task = use_hook(|| Signal::new(cb()));
  70. use_hook(|| {
  71. let mut changed = changed.take().unwrap();
  72. spawn(async move {
  73. loop {
  74. // Wait for the dependencies to change
  75. let _ = changed.next().await;
  76. // Stop the old task
  77. task.write().cancel();
  78. // Start a new task
  79. task.set(cb());
  80. }
  81. })
  82. });
  83. Resource {
  84. task,
  85. value,
  86. state,
  87. callback: cb,
  88. }
  89. }
  90. #[allow(unused)]
  91. pub struct Resource<T: 'static> {
  92. value: Signal<Option<T>>,
  93. task: Signal<Task>,
  94. state: Signal<UseResourceState>,
  95. callback: UseCallback<Task>,
  96. }
  97. /// A signal that represents the state of the resource
  98. // we might add more states (panicked, etc)
  99. #[derive(Clone, Copy, PartialEq, Hash, Eq, Debug)]
  100. pub enum UseResourceState {
  101. /// The resource's future is still running
  102. Pending,
  103. /// The resource's future has been forcefully stopped
  104. Stopped,
  105. /// The resource's future has been paused, tempoarily
  106. Paused,
  107. /// The resource's future has completed
  108. Ready,
  109. }
  110. impl<T> Resource<T> {
  111. /// Adds an explicit dependency to the resource. If the dependency changes, the resource's future will rerun.
  112. ///
  113. /// Signals will automatically be added as dependencies, so you don't need to call this method for them.
  114. ///
  115. /// NOTE: You must follow the rules of hooks when calling this method.
  116. ///
  117. /// ```rust
  118. /// # use dioxus::prelude::*;
  119. /// # async fn sleep(delay: u32) {}
  120. ///
  121. /// #[component]
  122. /// fn Comp(delay: u32) -> Element {
  123. /// // Because the resource subscribes to `delay` by adding it as a dependency, the resource's future will rerun every time `delay` changes.
  124. /// let current_weather = use_resource(move || async move {
  125. /// sleep(delay).await;
  126. /// "Sunny"
  127. /// })
  128. /// .use_dependencies((&delay,));
  129. ///
  130. /// rsx! {
  131. /// // the value of the resource can be polled to
  132. /// // conditionally render elements based off if it's future
  133. /// // finished (Some(Ok(_)), errored Some(Err(_)),
  134. /// // or is still running (None)
  135. /// match &*current_weather.read_unchecked() {
  136. /// Some(weather) => rsx! { "{weather}" },
  137. /// None => rsx! { p { "Loading..." } }
  138. /// }
  139. /// }
  140. /// }
  141. /// ```
  142. pub fn use_dependencies(self, dependency: impl dependency::Dependency) -> Self {
  143. let mut dependencies_signal = use_signal(|| dependency.out());
  144. let changed = { dependency.changed(&*dependencies_signal.read()) };
  145. if changed {
  146. dependencies_signal.set(dependency.out());
  147. }
  148. self
  149. }
  150. /// Restart the resource's future.
  151. ///
  152. /// Will not cancel the previous future, but will ignore any values that it
  153. /// generates.
  154. pub fn restart(&mut self) {
  155. self.task.write().cancel();
  156. let new_task = self.callback.call();
  157. self.task.set(new_task);
  158. }
  159. /// Forcefully cancel the resource's future.
  160. pub fn cancel(&mut self) {
  161. self.state.set(UseResourceState::Stopped);
  162. self.task.write().cancel();
  163. }
  164. /// Pause the resource's future.
  165. pub fn pause(&mut self) {
  166. self.state.set(UseResourceState::Paused);
  167. self.task.write().pause();
  168. }
  169. /// Resume the resource's future.
  170. pub fn resume(&mut self) {
  171. if self.finished() {
  172. return;
  173. }
  174. self.state.set(UseResourceState::Pending);
  175. self.task.write().resume();
  176. }
  177. /// Clear the resource's value.
  178. pub fn clear(&mut self) {
  179. self.value.write().take();
  180. }
  181. /// Get a handle to the inner task backing this resource
  182. /// Modify the task through this handle will cause inconsistent state
  183. pub fn task(&self) -> Task {
  184. self.task.cloned()
  185. }
  186. /// Is the resource's future currently finished running?
  187. ///
  188. /// Reading this does not subscribe to the future's state
  189. pub fn finished(&self) -> bool {
  190. matches!(
  191. *self.state.peek(),
  192. UseResourceState::Ready | UseResourceState::Stopped
  193. )
  194. }
  195. /// Get the current state of the resource's future.
  196. pub fn state(&self) -> ReadOnlySignal<UseResourceState> {
  197. self.state.into()
  198. }
  199. /// Get the current value of the resource's future.
  200. pub fn value(&self) -> ReadOnlySignal<Option<T>> {
  201. self.value.into()
  202. }
  203. }
  204. impl<T> From<Resource<T>> for ReadOnlySignal<Option<T>> {
  205. fn from(val: Resource<T>) -> Self {
  206. val.value.into()
  207. }
  208. }
  209. impl<T> Readable for Resource<T> {
  210. type Target = Option<T>;
  211. type Storage = UnsyncStorage;
  212. #[track_caller]
  213. fn try_read_unchecked(
  214. &self,
  215. ) -> Result<ReadableRef<'static, Self>, generational_box::BorrowError> {
  216. self.value.try_read_unchecked()
  217. }
  218. #[track_caller]
  219. fn peek_unchecked(&self) -> ReadableRef<'static, Self> {
  220. self.value.peek_unchecked()
  221. }
  222. }
  223. impl<T> IntoAttributeValue for Resource<T>
  224. where
  225. T: Clone + IntoAttributeValue,
  226. {
  227. fn into_value(self) -> dioxus_core::AttributeValue {
  228. self.with(|f| f.clone().into_value())
  229. }
  230. }
  231. impl<T> IntoDynNode for Resource<T>
  232. where
  233. T: Clone + IntoDynNode,
  234. {
  235. fn into_dyn_node(self) -> dioxus_core::DynamicNode {
  236. self().into_dyn_node()
  237. }
  238. }
  239. /// Allow calling a signal with signal() syntax
  240. ///
  241. /// Currently only limited to copy types, though could probably specialize for string/arc/rc
  242. impl<T: Clone> Deref for Resource<T> {
  243. type Target = dyn Fn() -> Option<T>;
  244. fn deref(&self) -> &Self::Target {
  245. Readable::deref_impl(self)
  246. }
  247. }