memo.rs 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. use crate::write::Writable;
  2. use crate::{read::Readable, ReadableRef, Signal};
  3. use crate::{read_impls, GlobalMemo};
  4. use crate::{CopyValue, ReadOnlySignal};
  5. use std::{
  6. cell::RefCell,
  7. ops::Deref,
  8. sync::{atomic::AtomicBool, Arc},
  9. };
  10. use dioxus_core::prelude::*;
  11. use futures_util::StreamExt;
  12. use generational_box::{AnyStorage, BorrowResult, UnsyncStorage};
  13. struct UpdateInformation<T> {
  14. dirty: Arc<AtomicBool>,
  15. callback: RefCell<Box<dyn FnMut() -> T>>,
  16. }
  17. #[doc = include_str!("../docs/memo.md")]
  18. #[doc(alias = "Selector")]
  19. #[doc(alias = "UseMemo")]
  20. #[doc(alias = "Memorize")]
  21. pub struct Memo<T: 'static> {
  22. inner: Signal<T>,
  23. update: CopyValue<UpdateInformation<T>>,
  24. }
  25. impl<T> From<Memo<T>> for ReadOnlySignal<T>
  26. where
  27. T: PartialEq,
  28. {
  29. fn from(val: Memo<T>) -> Self {
  30. ReadOnlySignal::new(val.inner)
  31. }
  32. }
  33. impl<T: 'static> Memo<T> {
  34. /// Create a new memo
  35. #[track_caller]
  36. pub fn new(f: impl FnMut() -> T + 'static) -> Self
  37. where
  38. T: PartialEq,
  39. {
  40. Self::new_with_location(f, std::panic::Location::caller())
  41. }
  42. /// Create a new memo with an explicit location
  43. pub fn new_with_location(
  44. mut f: impl FnMut() -> T + 'static,
  45. location: &'static std::panic::Location<'static>,
  46. ) -> Self
  47. where
  48. T: PartialEq,
  49. {
  50. let dirty = Arc::new(AtomicBool::new(false));
  51. let (tx, mut rx) = futures_channel::mpsc::unbounded();
  52. let callback = {
  53. let dirty = dirty.clone();
  54. move || {
  55. dirty.store(true, std::sync::atomic::Ordering::Relaxed);
  56. let _ = tx.unbounded_send(());
  57. }
  58. };
  59. let rc =
  60. ReactiveContext::new_with_callback(callback, current_scope_id().unwrap(), location);
  61. // Create a new signal in that context, wiring up its dependencies and subscribers
  62. let mut recompute = move || rc.reset_and_run_in(&mut f);
  63. let value = recompute();
  64. let recompute = RefCell::new(Box::new(recompute) as Box<dyn FnMut() -> T>);
  65. let update = CopyValue::new(UpdateInformation {
  66. dirty,
  67. callback: recompute,
  68. });
  69. let state: Signal<T> = Signal::new_with_caller(value, location);
  70. let memo = Memo {
  71. inner: state,
  72. update,
  73. };
  74. spawn_isomorphic(async move {
  75. while rx.next().await.is_some() {
  76. // Remove any pending updates
  77. while rx.try_next().is_ok() {}
  78. memo.recompute();
  79. }
  80. });
  81. memo
  82. }
  83. /// Creates a new [`GlobalMemo`] that can be used anywhere inside your dioxus app. This memo will automatically be created once per app the first time you use it.
  84. ///
  85. /// # Example
  86. /// ```rust, no_run
  87. /// # use dioxus::prelude::*;
  88. /// static SIGNAL: GlobalSignal<i32> = Signal::global(|| 0);
  89. /// // Create a new global memo that can be used anywhere in your app
  90. /// static DOUBLED: GlobalMemo<i32> = Memo::global(|| SIGNAL() * 2);
  91. ///
  92. /// fn App() -> Element {
  93. /// rsx! {
  94. /// button {
  95. /// // When SIGNAL changes, the memo will update because the SIGNAL is read inside DOUBLED
  96. /// onclick: move |_| *SIGNAL.write() += 1,
  97. /// "{DOUBLED}"
  98. /// }
  99. /// }
  100. /// }
  101. /// ```
  102. ///
  103. /// <div class="warning">
  104. ///
  105. /// Global memos are generally not recommended for use in libraries because it makes it more difficult to allow multiple instances of components you define in your library.
  106. ///
  107. /// </div>
  108. #[track_caller]
  109. pub const fn global(constructor: fn() -> T) -> GlobalMemo<T>
  110. where
  111. T: PartialEq,
  112. {
  113. GlobalMemo::new(constructor)
  114. }
  115. /// Rerun the computation and update the value of the memo if the result has changed.
  116. #[tracing::instrument(skip(self))]
  117. fn recompute(&self)
  118. where
  119. T: PartialEq,
  120. {
  121. let mut update_copy = self.update;
  122. let update_write = update_copy.write();
  123. let peak = self.inner.peek();
  124. let new_value = (update_write.callback.borrow_mut())();
  125. if new_value != *peak {
  126. drop(peak);
  127. let mut copy = self.inner;
  128. copy.set(new_value);
  129. update_write
  130. .dirty
  131. .store(false, std::sync::atomic::Ordering::Relaxed);
  132. }
  133. }
  134. /// Get the scope that the signal was created in.
  135. pub fn origin_scope(&self) -> ScopeId {
  136. self.inner.origin_scope()
  137. }
  138. /// Get the id of the signal.
  139. pub fn id(&self) -> generational_box::GenerationalBoxId {
  140. self.inner.id()
  141. }
  142. }
  143. impl<T> Readable for Memo<T>
  144. where
  145. T: PartialEq,
  146. {
  147. type Target = T;
  148. type Storage = UnsyncStorage;
  149. #[track_caller]
  150. fn try_read_unchecked(
  151. &self,
  152. ) -> Result<ReadableRef<'static, Self>, generational_box::BorrowError> {
  153. // Read the inner generational box instead of the signal so we have more fine grained control over exactly when the subscription happens
  154. let read = self.inner.inner.try_read_unchecked()?;
  155. let needs_update = self
  156. .update
  157. .read()
  158. .dirty
  159. .swap(false, std::sync::atomic::Ordering::Relaxed);
  160. let result = if needs_update {
  161. drop(read);
  162. // We shouldn't be subscribed to the value here so we don't trigger the scope we are currently in to rerun even though that scope got the latest value because we synchronously update the value: https://github.com/DioxusLabs/dioxus/issues/2416
  163. self.recompute();
  164. self.inner.inner.try_read_unchecked()
  165. } else {
  166. Ok(read)
  167. };
  168. // Subscribe to the current scope before returning the value
  169. if let Ok(read) = &result {
  170. if let Some(reactive_context) = ReactiveContext::current() {
  171. tracing::trace!("Subscribing to the reactive context {}", reactive_context);
  172. reactive_context.subscribe(read.subscribers.clone());
  173. }
  174. }
  175. result.map(|read| <UnsyncStorage as AnyStorage>::map(read, |v| &v.value))
  176. }
  177. /// Get the current value of the signal. **Unlike read, this will not subscribe the current scope to the signal which can cause parts of your UI to not update.**
  178. ///
  179. /// If the signal has been dropped, this will panic.
  180. #[track_caller]
  181. fn try_peek_unchecked(&self) -> BorrowResult<ReadableRef<'static, Self>> {
  182. self.inner.try_peek_unchecked()
  183. }
  184. }
  185. impl<T> IntoAttributeValue for Memo<T>
  186. where
  187. T: Clone + IntoAttributeValue + PartialEq,
  188. {
  189. fn into_value(self) -> dioxus_core::AttributeValue {
  190. self.with(|f| f.clone().into_value())
  191. }
  192. }
  193. impl<T> IntoDynNode for Memo<T>
  194. where
  195. T: Clone + IntoDynNode + PartialEq,
  196. {
  197. fn into_dyn_node(self) -> dioxus_core::DynamicNode {
  198. self().into_dyn_node()
  199. }
  200. }
  201. impl<T: 'static> PartialEq for Memo<T> {
  202. fn eq(&self, other: &Self) -> bool {
  203. self.inner == other.inner
  204. }
  205. }
  206. impl<T: Clone> Deref for Memo<T>
  207. where
  208. T: PartialEq,
  209. {
  210. type Target = dyn Fn() -> T;
  211. fn deref(&self) -> &Self::Target {
  212. unsafe { Readable::deref_impl(self) }
  213. }
  214. }
  215. read_impls!(Memo<T> where T: PartialEq);
  216. impl<T: 'static> Clone for Memo<T> {
  217. fn clone(&self) -> Self {
  218. *self
  219. }
  220. }
  221. impl<T: 'static> Copy for Memo<T> {}