add a way to add manual dependency tuple to memos and effects

This commit is contained in:
Evan Almloff committed 2024-03-13 09:54:48 -05:00
1 parent 2bbc609082
commit 0951a389f7
7 files changed
+106 -105

No files matched your search

+35 -1
View File
@@ -1,6 +1,6 @@
use crate::write::Writable;
use crate::{read::Readable, ReactiveContext, ReadableRef, Signal};
use crate::{CopyValue, ReadOnlySignal};
use crate::{CopyValue, Dependency, ReadOnlySignal};
use std::rc::Rc;
use std::{
cell::RefCell,
@@ -153,6 +153,40 @@ impl<T: 'static> Memo<T> {
pub fn id(&self) -> generational_box::GenerationalBoxId {
self.inner.id()
}
/// Adds an explicit dependency to the memo. If the dependency changes, the memo will rerun.
///
/// Signals will automatically be added as dependencies, so you don't need to call this method for them.
///
/// NOTE: You must follow the rules of hooks when calling this method.
///
/// ```rust
/// # use dioxus::prelude::*;
/// # async fn sleep(delay: u32) {}
///
/// #[component]
/// fn Comp(count: u32) -> Element {
/// // Because the resource subscribes to `delay` by adding it as a dependency, the memo will rerun every time `count` changes.
/// let new_count = use_memo(move || async move {
/// count + 1
/// })
/// .use_dependencies((&count,));
///
/// todo!()
/// }
/// ```
pub fn use_dependencies(self, dependency: impl Dependency) -> Self
where
T: PartialEq,
{
let mut dependencies_signal = use_hook(|| CopyValue::new(dependency.out()));
let changed = { dependency.changed(&*dependencies_signal.read()) };
if changed {
dependencies_signal.set(dependency.out());
self.recompute();
}
self
}
}
impl<T> Readable for Memo<T>