use_resource.rs 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  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. ///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. impl<T> Clone for Resource<T> {
  98. fn clone(&self) -> Self {
  99. *self
  100. }
  101. }
  102. impl<T> Copy for Resource<T> {}
  103. /// A signal that represents the state of the resource
  104. // we might add more states (panicked, etc)
  105. #[derive(Clone, Copy, PartialEq, Hash, Eq, Debug)]
  106. pub enum UseResourceState {
  107. /// The resource's future is still running
  108. Pending,
  109. /// The resource's future has been forcefully stopped
  110. Stopped,
  111. /// The resource's future has been paused, tempoarily
  112. Paused,
  113. /// The resource's future has completed
  114. Ready,
  115. }
  116. impl<T> Resource<T> {
  117. /// Restart the resource's future.
  118. ///
  119. /// Will not cancel the previous future, but will ignore any values that it
  120. /// generates.
  121. pub fn restart(&mut self) {
  122. self.task.write().cancel();
  123. let new_task = self.callback.call();
  124. self.task.set(new_task);
  125. }
  126. /// Forcefully cancel the resource's future.
  127. pub fn cancel(&mut self) {
  128. self.state.set(UseResourceState::Stopped);
  129. self.task.write().cancel();
  130. }
  131. /// Pause the resource's future.
  132. pub fn pause(&mut self) {
  133. self.state.set(UseResourceState::Paused);
  134. self.task.write().pause();
  135. }
  136. /// Resume the resource's future.
  137. pub fn resume(&mut self) {
  138. if self.finished() {
  139. return;
  140. }
  141. self.state.set(UseResourceState::Pending);
  142. self.task.write().resume();
  143. }
  144. /// Clear the resource's value.
  145. pub fn clear(&mut self) {
  146. self.value.write().take();
  147. }
  148. /// Get a handle to the inner task backing this resource
  149. /// Modify the task through this handle will cause inconsistent state
  150. pub fn task(&self) -> Task {
  151. self.task.cloned()
  152. }
  153. /// Is the resource's future currently finished running?
  154. ///
  155. /// Reading this does not subscribe to the future's state
  156. pub fn finished(&self) -> bool {
  157. matches!(
  158. *self.state.peek(),
  159. UseResourceState::Ready | UseResourceState::Stopped
  160. )
  161. }
  162. /// Get the current state of the resource's future.
  163. pub fn state(&self) -> ReadOnlySignal<UseResourceState> {
  164. self.state.into()
  165. }
  166. /// Get the current value of the resource's future.
  167. pub fn value(&self) -> ReadOnlySignal<Option<T>> {
  168. self.value.into()
  169. }
  170. }
  171. impl<T> From<Resource<T>> for ReadOnlySignal<Option<T>> {
  172. fn from(val: Resource<T>) -> Self {
  173. val.value.into()
  174. }
  175. }
  176. impl<T> Readable for Resource<T> {
  177. type Target = Option<T>;
  178. type Storage = UnsyncStorage;
  179. #[track_caller]
  180. fn try_read_unchecked(
  181. &self,
  182. ) -> Result<ReadableRef<'static, Self>, generational_box::BorrowError> {
  183. self.value.try_read_unchecked()
  184. }
  185. #[track_caller]
  186. fn peek_unchecked(&self) -> ReadableRef<'static, Self> {
  187. self.value.peek_unchecked()
  188. }
  189. }
  190. impl<T> IntoAttributeValue for Resource<T>
  191. where
  192. T: Clone + IntoAttributeValue,
  193. {
  194. fn into_value(self) -> dioxus_core::AttributeValue {
  195. self.with(|f| f.clone().into_value())
  196. }
  197. }
  198. impl<T> IntoDynNode for Resource<T>
  199. where
  200. T: Clone + IntoDynNode,
  201. {
  202. fn into_dyn_node(self) -> dioxus_core::DynamicNode {
  203. self().into_dyn_node()
  204. }
  205. }
  206. /// Allow calling a signal with signal() syntax
  207. ///
  208. /// Currently only limited to copy types, though could probably specialize for string/arc/rc
  209. impl<T: Clone> Deref for Resource<T> {
  210. type Target = dyn Fn() -> Option<T>;
  211. fn deref(&self) -> &Self::Target {
  212. Readable::deref_impl(self)
  213. }
  214. }