signal.rs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670
  1. use crate::{default_impl, fmt_impls, write_impls};
  2. use crate::{read::*, write::*, CopyValue, GlobalMemo, GlobalSignal, ReadableRef};
  3. use crate::{Memo, WritableRef};
  4. use dioxus_core::prelude::*;
  5. use generational_box::{AnyStorage, Storage, SyncStorage, UnsyncStorage};
  6. use std::sync::Arc;
  7. use std::{
  8. any::Any,
  9. collections::HashSet,
  10. ops::{Deref, DerefMut},
  11. sync::Mutex,
  12. };
  13. #[doc = include_str!("../docs/signals.md")]
  14. #[doc(alias = "State")]
  15. #[doc(alias = "UseState")]
  16. #[doc(alias = "UseRef")]
  17. pub struct Signal<T: 'static, S: Storage<SignalData<T>> = UnsyncStorage> {
  18. pub(crate) inner: CopyValue<SignalData<T>, S>,
  19. }
  20. /// A signal that can safely shared between threads.
  21. #[doc(alias = "SendSignal")]
  22. #[doc(alias = "UseRwLock")]
  23. #[doc(alias = "UseRw")]
  24. #[doc(alias = "UseMutex")]
  25. pub type SyncSignal<T> = Signal<T, SyncStorage>;
  26. /// The data stored for tracking in a signal.
  27. pub struct SignalData<T> {
  28. pub(crate) subscribers: Arc<Mutex<HashSet<ReactiveContext>>>,
  29. pub(crate) value: T,
  30. }
  31. impl<T: 'static> Signal<T> {
  32. /// Creates a new [`Signal`]. Signals are a Copy state management solution with automatic dependency tracking.
  33. ///
  34. /// <div class="warning">
  35. ///
  36. /// This function should generally only be called inside hooks. The signal that this function creates is owned by the current component and will only be dropped when the component is dropped. If you call this function outside of a hook many times, you will leak memory until the component is dropped.
  37. ///
  38. /// ```rust
  39. /// # use dioxus::prelude::*;
  40. /// fn MyComponent() {
  41. /// // ❌ Every time MyComponent runs, it will create a new signal that is only dropped when MyComponent is dropped
  42. /// let signal = Signal::new(0);
  43. /// use_context_provider(|| signal);
  44. /// // ✅ Since the use_context_provider hook only runs when the component is created, the signal will only be created once and it will be dropped when MyComponent is dropped
  45. /// let signal = use_context_provider(|| Signal::new(0));
  46. /// }
  47. /// ```
  48. ///
  49. /// </div>
  50. #[track_caller]
  51. pub fn new(value: T) -> Self {
  52. Self::new_maybe_sync(value)
  53. }
  54. /// Create a new signal with a custom owner scope. The signal will be dropped when the owner scope is dropped instead of the current scope.
  55. #[track_caller]
  56. pub fn new_in_scope(value: T, owner: ScopeId) -> Self {
  57. Self::new_maybe_sync_in_scope(value, owner)
  58. }
  59. /// Creates a new [`GlobalSignal`] that can be used anywhere inside your dioxus app. This signal will automatically be created once per app the first time you use it.
  60. ///
  61. /// # Example
  62. /// ```rust, no_run
  63. /// # use dioxus::prelude::*;
  64. /// // Create a new global signal that can be used anywhere in your app
  65. /// static SIGNAL: GlobalSignal<i32> = Signal::global(|| 0);
  66. ///
  67. /// fn App() -> Element {
  68. /// rsx! {
  69. /// button {
  70. /// onclick: move |_| *SIGNAL.write() += 1,
  71. /// "{SIGNAL}"
  72. /// }
  73. /// }
  74. /// }
  75. /// ```
  76. ///
  77. /// <div class="warning">
  78. ///
  79. /// Global signals 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.
  80. ///
  81. /// </div>
  82. #[track_caller]
  83. pub const fn global(constructor: fn() -> T) -> GlobalSignal<T> {
  84. GlobalSignal::new(constructor)
  85. }
  86. }
  87. impl<T: PartialEq + 'static> Signal<T> {
  88. /// 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.
  89. ///
  90. /// # Example
  91. /// ```rust, no_run
  92. /// # use dioxus::prelude::*;
  93. /// static SIGNAL: GlobalSignal<i32> = Signal::global(|| 0);
  94. /// // Create a new global memo that can be used anywhere in your app
  95. /// static DOUBLED: GlobalMemo<i32> = Signal::global_memo(|| SIGNAL() * 2);
  96. ///
  97. /// fn App() -> Element {
  98. /// rsx! {
  99. /// button {
  100. /// // When SIGNAL changes, the memo will update because the SIGNAL is read inside DOUBLED
  101. /// onclick: move |_| *SIGNAL.write() += 1,
  102. /// "{DOUBLED}"
  103. /// }
  104. /// }
  105. /// }
  106. /// ```
  107. ///
  108. /// <div class="warning">
  109. ///
  110. /// 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.
  111. ///
  112. /// </div>
  113. #[track_caller]
  114. pub const fn global_memo(constructor: fn() -> T) -> GlobalMemo<T> {
  115. GlobalMemo::new(constructor)
  116. }
  117. /// Creates a new unsync Selector. The selector will be run immediately and whenever any signal it reads changes.
  118. ///
  119. /// Selectors can be used to efficiently compute derived data from signals.
  120. #[track_caller]
  121. pub fn memo(f: impl FnMut() -> T + 'static) -> Memo<T> {
  122. Memo::new(f)
  123. }
  124. /// Creates a new unsync Selector with an explicit location. The selector will be run immediately and whenever any signal it reads changes.
  125. ///
  126. /// Selectors can be used to efficiently compute derived data from signals.
  127. pub fn memo_with_location(
  128. f: impl FnMut() -> T + 'static,
  129. location: &'static std::panic::Location<'static>,
  130. ) -> Memo<T> {
  131. Memo::new_with_location(f, location)
  132. }
  133. }
  134. impl<T: 'static, S: Storage<SignalData<T>>> Signal<T, S> {
  135. /// Creates a new Signal. Signals are a Copy state management solution with automatic dependency tracking.
  136. #[track_caller]
  137. #[tracing::instrument(skip(value))]
  138. pub fn new_maybe_sync(value: T) -> Self {
  139. Self {
  140. inner: CopyValue::<SignalData<T>, S>::new_maybe_sync(SignalData {
  141. subscribers: Default::default(),
  142. value,
  143. }),
  144. }
  145. }
  146. /// Creates a new Signal with an explicit caller. Signals are a Copy state management solution with automatic dependency tracking.
  147. ///
  148. /// This method can be used to provide the correct caller information for signals that are created in closures:
  149. ///
  150. /// ```rust
  151. /// # use dioxus::prelude::*;
  152. /// #[track_caller]
  153. /// fn use_my_signal(function: impl FnOnce() -> i32) -> Signal<i32> {
  154. /// // We capture the caller information outside of the closure so that it points to the caller of use_my_custom_hook instead of the closure
  155. /// let caller = std::panic::Location::caller();
  156. /// use_hook(move || Signal::new_with_caller(function(), caller))
  157. /// }
  158. /// ```
  159. pub fn new_with_caller(value: T, caller: &'static std::panic::Location<'static>) -> Self {
  160. Self {
  161. inner: CopyValue::new_with_caller(
  162. SignalData {
  163. subscribers: Default::default(),
  164. value,
  165. },
  166. caller,
  167. ),
  168. }
  169. }
  170. /// Create a new signal with a custom owner scope. The signal will be dropped when the owner scope is dropped instead of the current scope.
  171. #[track_caller]
  172. #[tracing::instrument(skip(value))]
  173. pub fn new_maybe_sync_in_scope(value: T, owner: ScopeId) -> Self {
  174. Self {
  175. inner: CopyValue::<SignalData<T>, S>::new_maybe_sync_in_scope(
  176. SignalData {
  177. subscribers: Default::default(),
  178. value,
  179. },
  180. owner,
  181. ),
  182. }
  183. }
  184. /// Drop the value out of the signal, invalidating the signal in the process.
  185. pub fn manually_drop(&self) -> Option<T> {
  186. self.inner.manually_drop().map(|i| i.value)
  187. }
  188. /// Get the scope the signal was created in.
  189. pub fn origin_scope(&self) -> ScopeId {
  190. self.inner.origin_scope()
  191. }
  192. fn update_subscribers(&self) {
  193. {
  194. let inner = self.inner.read();
  195. // We cannot hold the subscribers lock while calling mark_dirty, because mark_dirty can run user code which may cause a new subscriber to be added. If we hold the lock, we will deadlock.
  196. #[allow(clippy::mutable_key_type)]
  197. let mut subscribers = std::mem::take(&mut *inner.subscribers.lock().unwrap());
  198. subscribers.retain(|reactive_context| reactive_context.mark_dirty());
  199. // Extend the subscribers list instead of overwriting it in case a subscriber is added while reactive contexts are marked dirty
  200. inner.subscribers.lock().unwrap().extend(subscribers);
  201. }
  202. }
  203. /// Get the generational id of the signal.
  204. pub fn id(&self) -> generational_box::GenerationalBoxId {
  205. self.inner.id()
  206. }
  207. /// **This pattern is no longer recommended. Prefer [`peek`](Signal::peek) or creating new signals instead.**
  208. ///
  209. /// This function is the equivalent of the [write_silent](https://docs.rs/dioxus/latest/dioxus/prelude/struct.UseRef.html#method.write_silent) method on use_ref.
  210. ///
  211. /// ## What you should use instead
  212. ///
  213. /// ### Reading and Writing to data in the same scope
  214. ///
  215. /// Reading and writing to the same signal in the same scope will cause that scope to rerun forever:
  216. /// ```rust, no_run
  217. /// # use dioxus::prelude::*;
  218. /// let mut signal = use_signal(|| 0);
  219. /// // This makes the scope rerun whenever we write to the signal
  220. /// println!("{}", *signal.read());
  221. /// // This will rerun the scope because we read the signal earlier in the same scope
  222. /// *signal.write() += 1;
  223. /// ```
  224. ///
  225. /// You may have used the write_silent method to avoid this infinite loop with use_ref like this:
  226. /// ```rust, no_run
  227. /// # use dioxus::prelude::*;
  228. /// let signal = use_signal(|| 0);
  229. /// // This makes the scope rerun whenever we write to the signal
  230. /// println!("{}", *signal.read());
  231. /// // Write silent will not rerun any subscribers
  232. /// *signal.write_silent() += 1;
  233. /// ```
  234. ///
  235. /// Instead you can use the [`peek`](Signal::peek) and [`write`](Signal::write) methods instead. The peek method will not subscribe to the current scope which will avoid an infinite loop if you are reading and writing to the same signal in the same scope.
  236. /// ```rust, no_run
  237. /// # use dioxus::prelude::*;
  238. /// let mut signal = use_signal(|| 0);
  239. /// // Peek will read the value but not subscribe to the current scope
  240. /// println!("{}", *signal.peek());
  241. /// // Write will update any subscribers which does not include the current scope
  242. /// *signal.write() += 1;
  243. /// ```
  244. ///
  245. /// ### Reading and Writing to different data
  246. ///
  247. ///
  248. ///
  249. /// ## Why is this pattern no longer recommended?
  250. ///
  251. /// This pattern is no longer recommended because it is very easy to allow your state and UI to grow out of sync. `write_silent` globally opts out of automatic state updates which can be difficult to reason about.
  252. ///
  253. ///
  254. /// Lets take a look at an example:
  255. /// main.rs:
  256. /// ```rust, no_run
  257. /// # use dioxus::prelude::*;
  258. /// # fn Child() -> Element { unimplemented!() }
  259. /// fn app() -> Element {
  260. /// let signal = use_context_provider(|| Signal::new(0));
  261. ///
  262. /// // We want to log the value of the signal whenever the app component reruns
  263. /// println!("{}", *signal.read());
  264. ///
  265. /// rsx! {
  266. /// button {
  267. /// // If we don't want to rerun the app component when the button is clicked, we can use write_silent
  268. /// onclick: move |_| *signal.write_silent() += 1,
  269. /// "Increment"
  270. /// }
  271. /// Child {}
  272. /// }
  273. /// }
  274. /// ```
  275. /// child.rs:
  276. /// ```rust, no_run
  277. /// # use dioxus::prelude::*;
  278. /// fn Child() -> Element {
  279. /// let signal: Signal<i32> = use_context();
  280. ///
  281. /// // It is difficult to tell that changing the button to use write_silent in the main.rs file will cause UI to be out of sync in a completely different file
  282. /// rsx! {
  283. /// "{signal}"
  284. /// }
  285. /// }
  286. /// ```
  287. ///
  288. /// Instead [`peek`](Signal::peek) locally opts out of automatic state updates explicitly for a specific read which is easier to reason about.
  289. ///
  290. /// Here is the same example using peek:
  291. /// main.rs:
  292. /// ```rust, no_run
  293. /// # use dioxus::prelude::*;
  294. /// # fn Child() -> Element { unimplemented!() }
  295. /// fn app() -> Element {
  296. /// let mut signal = use_context_provider(|| Signal::new(0));
  297. ///
  298. /// // We want to log the value of the signal whenever the app component reruns, but we don't want to rerun the app component when the signal is updated so we use peek instead of read
  299. /// println!("{}", *signal.peek());
  300. ///
  301. /// rsx! {
  302. /// button {
  303. /// // We can use write like normal and update the child component automatically
  304. /// onclick: move |_| *signal.write() += 1,
  305. /// "Increment"
  306. /// }
  307. /// Child {}
  308. /// }
  309. /// }
  310. /// ```
  311. /// child.rs:
  312. /// ```rust, no_run
  313. /// # use dioxus::prelude::*;
  314. /// fn Child() -> Element {
  315. /// let signal: Signal<i32> = use_context();
  316. ///
  317. /// rsx! {
  318. /// "{signal}"
  319. /// }
  320. /// }
  321. /// ```
  322. #[track_caller]
  323. #[deprecated = "This pattern is no longer recommended. Prefer `peek` or creating new signals instead."]
  324. pub fn write_silent(&self) -> S::Mut<'static, T> {
  325. S::map_mut(self.inner.write_unchecked(), |inner| &mut inner.value)
  326. }
  327. }
  328. impl<T, S: Storage<SignalData<T>>> Readable for Signal<T, S> {
  329. type Target = T;
  330. type Storage = S;
  331. #[track_caller]
  332. fn try_read_unchecked(
  333. &self,
  334. ) -> Result<ReadableRef<'static, Self>, generational_box::BorrowError> {
  335. let inner = self.inner.try_read_unchecked()?;
  336. if let Some(reactive_context) = ReactiveContext::current() {
  337. tracing::trace!("Subscribing to the reactive context {}", reactive_context);
  338. reactive_context.subscribe(inner.subscribers.clone());
  339. }
  340. Ok(S::map(inner, |v| &v.value))
  341. }
  342. /// 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.**
  343. ///
  344. /// If the signal has been dropped, this will panic.
  345. #[track_caller]
  346. fn peek_unchecked(&self) -> ReadableRef<'static, Self> {
  347. let inner = self.inner.try_read_unchecked().unwrap();
  348. S::map(inner, |v| &v.value)
  349. }
  350. }
  351. impl<T: 'static, S: Storage<SignalData<T>>> Writable for Signal<T, S> {
  352. type Mut<'a, R: ?Sized + 'static> = Write<'a, R, S>;
  353. fn map_mut<I: ?Sized, U: ?Sized + 'static, F: FnOnce(&mut I) -> &mut U>(
  354. ref_: Self::Mut<'_, I>,
  355. f: F,
  356. ) -> Self::Mut<'_, U> {
  357. Write::map(ref_, f)
  358. }
  359. fn try_map_mut<
  360. I: ?Sized + 'static,
  361. U: ?Sized + 'static,
  362. F: FnOnce(&mut I) -> Option<&mut U>,
  363. >(
  364. ref_: Self::Mut<'_, I>,
  365. f: F,
  366. ) -> Option<Self::Mut<'_, U>> {
  367. Write::filter_map(ref_, f)
  368. }
  369. fn downcast_lifetime_mut<'a: 'b, 'b, R: ?Sized + 'static>(
  370. mut_: Self::Mut<'a, R>,
  371. ) -> Self::Mut<'b, R> {
  372. Write::downcast_lifetime(mut_)
  373. }
  374. #[track_caller]
  375. fn try_write_unchecked(
  376. &self,
  377. ) -> Result<WritableRef<'static, Self>, generational_box::BorrowMutError> {
  378. #[cfg(debug_assertions)]
  379. let origin = std::panic::Location::caller();
  380. self.inner.try_write_unchecked().map(|inner| {
  381. let borrow = S::map_mut(inner, |v| &mut v.value);
  382. Write {
  383. write: borrow,
  384. drop_signal: Box::new(SignalSubscriberDrop {
  385. signal: *self,
  386. #[cfg(debug_assertions)]
  387. origin,
  388. }),
  389. }
  390. })
  391. }
  392. }
  393. impl<T> IntoAttributeValue for Signal<T>
  394. where
  395. T: Clone + IntoAttributeValue,
  396. {
  397. fn into_value(self) -> dioxus_core::AttributeValue {
  398. self.with(|f| f.clone().into_value())
  399. }
  400. }
  401. impl<T> IntoDynNode for Signal<T>
  402. where
  403. T: Clone + IntoDynNode,
  404. {
  405. fn into_dyn_node(self) -> dioxus_core::DynamicNode {
  406. self().into_dyn_node()
  407. }
  408. }
  409. impl<T: 'static, S: Storage<SignalData<T>>> PartialEq for Signal<T, S> {
  410. fn eq(&self, other: &Self) -> bool {
  411. self.inner == other.inner
  412. }
  413. }
  414. impl<T: 'static, S: Storage<SignalData<T>>> Eq for Signal<T, S> {}
  415. /// Allow calling a signal with signal() syntax
  416. ///
  417. /// Currently only limited to copy types, though could probably specialize for string/arc/rc
  418. impl<T: Clone, S: Storage<SignalData<T>> + 'static> Deref for Signal<T, S> {
  419. type Target = dyn Fn() -> T;
  420. fn deref(&self) -> &Self::Target {
  421. Readable::deref_impl(self)
  422. }
  423. }
  424. #[cfg(feature = "serialize")]
  425. impl<T: serde::Serialize + 'static, Store: Storage<SignalData<T>>> serde::Serialize
  426. for Signal<T, Store>
  427. {
  428. fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
  429. self.read().serialize(serializer)
  430. }
  431. }
  432. #[cfg(feature = "serialize")]
  433. impl<'de, T: serde::Deserialize<'de> + 'static, Store: Storage<SignalData<T>>>
  434. serde::Deserialize<'de> for Signal<T, Store>
  435. {
  436. fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
  437. Ok(Self::new_maybe_sync(T::deserialize(deserializer)?))
  438. }
  439. }
  440. /// A mutable reference to a signal's value.
  441. ///
  442. /// T is the current type of the write
  443. /// S is the storage type of the signal
  444. pub struct Write<'a, T: ?Sized + 'static, S: AnyStorage = UnsyncStorage> {
  445. write: S::Mut<'a, T>,
  446. drop_signal: Box<dyn Any>,
  447. }
  448. impl<'a, T: ?Sized + 'static, S: AnyStorage> Write<'a, T, S> {
  449. /// Map the mutable reference to the signal's value to a new type.
  450. pub fn map<O: ?Sized>(myself: Self, f: impl FnOnce(&mut T) -> &mut O) -> Write<'a, O, S> {
  451. let Self {
  452. write, drop_signal, ..
  453. } = myself;
  454. Write {
  455. write: S::map_mut(write, f),
  456. drop_signal,
  457. }
  458. }
  459. /// Try to map the mutable reference to the signal's value to a new type
  460. pub fn filter_map<O: ?Sized>(
  461. myself: Self,
  462. f: impl FnOnce(&mut T) -> Option<&mut O>,
  463. ) -> Option<Write<'a, O, S>> {
  464. let Self {
  465. write, drop_signal, ..
  466. } = myself;
  467. let write = S::try_map_mut(write, f);
  468. write.map(|write| Write { write, drop_signal })
  469. }
  470. /// Downcast the lifetime of the mutable reference to the signal's value.
  471. ///
  472. /// This function enforces the variance of the lifetime parameter `'a` in Mut. Rust will typically infer this cast with a concrete type, but it cannot with a generic type.
  473. pub fn downcast_lifetime<'b>(mut_: Self) -> Write<'b, T, S>
  474. where
  475. 'a: 'b,
  476. {
  477. Write {
  478. write: S::downcast_lifetime_mut(mut_.write),
  479. drop_signal: mut_.drop_signal,
  480. }
  481. }
  482. }
  483. impl<T: ?Sized + 'static, S: AnyStorage> Deref for Write<'_, T, S> {
  484. type Target = T;
  485. fn deref(&self) -> &Self::Target {
  486. &self.write
  487. }
  488. }
  489. impl<T: ?Sized, S: AnyStorage> DerefMut for Write<'_, T, S> {
  490. fn deref_mut(&mut self) -> &mut Self::Target {
  491. &mut self.write
  492. }
  493. }
  494. #[allow(unused)]
  495. const SIGNAL_READ_WRITE_SAME_SCOPE_HELP: &str = r#"This issue is caused by reading and writing to the same signal in a reactive scope. Components, effects, memos, and resources each have their own a reactive scopes. Reactive scopes rerun when any signal you read inside of them are changed. If you read and write to the same signal in the same scope, the write will cause the scope to rerun and trigger the write again. This can cause an infinite loop.
  496. You can fix the issue by either:
  497. 1) Splitting up your state and Writing, reading to different signals:
  498. For example, you could change this broken code:
  499. #[derive(Clone, Copy)]
  500. struct Counts {
  501. count1: i32,
  502. count2: i32,
  503. }
  504. fn app() -> Element {
  505. let mut counts = use_signal(|| Counts { count1: 0, count2: 0 });
  506. use_effect(move || {
  507. // This effect both reads and writes to counts
  508. counts.write().count1 = counts().count2;
  509. })
  510. }
  511. Into this working code:
  512. fn app() -> Element {
  513. let mut count1 = use_signal(|| 0);
  514. let mut count2 = use_signal(|| 0);
  515. use_effect(move || {
  516. count1.write(count2());
  517. });
  518. }
  519. 2) Reading and Writing to the same signal in different scopes:
  520. For example, you could change this broken code:
  521. fn app() -> Element {
  522. let mut count = use_signal(|| 0);
  523. use_effect(move || {
  524. // This effect both reads and writes to count
  525. println!("{}", count());
  526. count.write(count());
  527. });
  528. }
  529. To this working code:
  530. fn app() -> Element {
  531. let mut count = use_signal(|| 0);
  532. use_effect(move || {
  533. count.write(count());
  534. });
  535. use_effect(move || {
  536. println!("{}", count());
  537. });
  538. }
  539. "#;
  540. struct SignalSubscriberDrop<T: 'static, S: Storage<SignalData<T>>> {
  541. signal: Signal<T, S>,
  542. #[cfg(debug_assertions)]
  543. origin: &'static std::panic::Location<'static>,
  544. }
  545. pub mod warnings {
  546. //! Warnings that can be triggered by suspicious usage of signals
  547. use super::*;
  548. use ::warnings::warning;
  549. /// Check if the write happened during a render. If it did, warn the user that this is generally a bad practice.
  550. #[warning]
  551. pub fn signal_write_in_component_body(origin: &'static std::panic::Location<'static>) {
  552. // Check if the write happened during a render. If it did, we should warn the user that this is generally a bad practice.
  553. if dioxus_core::vdom_is_rendering() {
  554. tracing::warn!(
  555. "Write on signal at {} happened while a component was running. Writing to signals during a render can cause infinite rerenders when you read the same signal in the component. Consider writing to the signal in an effect, future, or event handler if possible.",
  556. origin
  557. );
  558. }
  559. }
  560. /// Check if the write happened during a scope that the signal is also subscribed to. If it did, trigger a warning because it will likely cause an infinite loop.
  561. #[warning]
  562. pub fn signal_read_and_write_in_reactive_scope<T: 'static, S: Storage<SignalData<T>>>(
  563. origin: &'static std::panic::Location<'static>,
  564. signal: Signal<T, S>,
  565. ) {
  566. // Check if the write happened during a scope that the signal is also subscribed to. If it did, this will probably cause an infinite loop.
  567. if let Some(reactive_context) = ReactiveContext::current() {
  568. if let Ok(inner) = signal.inner.try_read() {
  569. if let Ok(subscribers) = inner.subscribers.lock() {
  570. for subscriber in subscribers.iter() {
  571. if reactive_context == *subscriber {
  572. tracing::warn!(
  573. "Write on signal at {origin} finished in {reactive_context} which is also subscribed to the signal. This will likely cause an infinite loop. When the write finishes, {reactive_context} will rerun which may cause the write to be rerun again.\nHINT:\n{SIGNAL_READ_WRITE_SAME_SCOPE_HELP}",
  574. );
  575. }
  576. }
  577. }
  578. }
  579. }
  580. }
  581. }
  582. #[allow(clippy::no_effect)]
  583. impl<T: 'static, S: Storage<SignalData<T>>> Drop for SignalSubscriberDrop<T, S> {
  584. fn drop(&mut self) {
  585. tracing::trace!(
  586. "Write on signal at {} finished, updating subscribers",
  587. self.origin
  588. );
  589. warnings::signal_write_in_component_body(self.origin);
  590. warnings::signal_read_and_write_in_reactive_scope::<T, S>(self.origin, self.signal);
  591. self.signal.update_subscribers();
  592. }
  593. }
  594. fmt_impls!(Signal<T, S: Storage<SignalData<T>>>);
  595. default_impl!(Signal<T, S: Storage<SignalData<T>>>);
  596. write_impls!(Signal<T, S: Storage<SignalData<T>>>);
  597. impl<T: 'static, S: Storage<SignalData<T>>> Clone for Signal<T, S> {
  598. fn clone(&self) -> Self {
  599. *self
  600. }
  601. }
  602. impl<T: 'static, S: Storage<SignalData<T>>> Copy for Signal<T, S> {}