1
0

use_resource.rs 6.4 KB

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