1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
use super::{use_ref, Deps, RefContainer};
use crate::{Persisted, PersistedOrigin};
use std::cell::Ref;
use wasm_bindgen::UnwrapThrowExt;
#[derive(Debug)]
pub struct Memo<T>(RefContainer<Option<T>>);
impl<T: 'static> Memo<T> {
pub fn value(&self) -> Ref<'_, T> {
Ref::map(self.0.current(), |x| {
x.as_ref().expect_throw("no memo data available")
})
}
}
impl<T: 'static> Persisted for Memo<T> {
fn ptr(&self) -> PersistedOrigin {
self.0.ptr()
}
}
impl<T> Clone for Memo<T> {
fn clone(&self) -> Self {
Self(self.0.clone())
}
}
pub fn use_memo<T, D>(create: impl FnOnce() -> T, deps: Deps<D>) -> Memo<T>
where
T: 'static,
D: PartialEq + 'static,
{
let mut deps_ref_container = use_ref(None::<Deps<D>>);
let mut value_ref_container = use_ref(None::<T>);
let need_update = {
let current = deps_ref_container.current();
let old_deps = current.as_ref();
deps.is_all() || Some(&deps) != old_deps
};
if need_update {
deps_ref_container.set_current(Some(deps));
value_ref_container.set_current(Some(create()));
}
Memo(value_ref_container)
}