use_resource.rs 7.2 KB

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