Move to a generic GlobalLazy<T> (#2851)

* Expose a generic lazy type

* Switch to generic lazy globals

* simplify global lazy context a bit

* rename LazyGlobal to Global

* use Memo::global in more examples

* Fix soundness issue with deref_impl. It relies on the size of self, so it cannot be safe

* add a comment about safety

* Make clippy happy

* fix formatting

* Restore changes to signal impl

* Add helper methods for global signal and global memo to make getting the inner value easier
This commit is contained in:
Evan Almloff authored and GitHub committed 2024-08-16 17:57:41 -05:00
1 parent 668d5415c8
commit b47a6cf83e
13 files changed
+281 -289

No files matched your search

+35 -2
View File
@@ -1,6 +1,6 @@
use crate::read_impls;
use crate::write::Writable;
use crate::{read::Readable, ReadableRef, Signal};
use crate::{read_impls, GlobalMemo};
use crate::{CopyValue, ReadOnlySignal};
use std::{
cell::RefCell,
@@ -92,6 +92,39 @@ impl<T: 'static> Memo<T> {
memo
}
/// 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.
///
/// # Example
/// ```rust, no_run
/// # use dioxus::prelude::*;
/// static SIGNAL: GlobalSignal<i32> = Signal::global(|| 0);
/// // Create a new global memo that can be used anywhere in your app
/// static DOUBLED: GlobalMemo<i32> = Memo::global(|| SIGNAL() * 2);
///
/// fn App() -> Element {
/// rsx! {
/// button {
/// // When SIGNAL changes, the memo will update because the SIGNAL is read inside DOUBLED
/// onclick: move |_| *SIGNAL.write() += 1,
/// "{DOUBLED}"
/// }
/// }
/// }
/// ```
///
/// <div class="warning">
///
/// 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.
///
/// </div>
#[track_caller]
pub const fn global(constructor: fn() -> T) -> GlobalMemo<T>
where
T: PartialEq,
{
GlobalMemo::new(constructor)
}
/// Rerun the computation and update the value of the memo if the result has changed.
#[tracing::instrument(skip(self))]
fn recompute(&self)
@@ -200,7 +233,7 @@ where
type Target = dyn Fn() -> T;
fn deref(&self) -> &Self::Target {
Readable::deref_impl(self)
unsafe { Readable::deref_impl(self) }
}
}