Skip to content

Commit 7a9d3fc

Browse files
committed
docs(cache): Added important notes on memory management for Memo and Signal types, emphasizing the use of Weak types when referencing between structures to avoid memory leaks and circular references.
1 parent 628ac98 commit 7a9d3fc

File tree

2 files changed

+23
-0
lines changed

2 files changed

+23
-0
lines changed

cache/src/memo.rs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,14 @@ use crate::{IObservable, memo_stack, store_in_cache, touch};
1818
/// # Type Parameters
1919
///
2020
/// - `T`: The result type of the computation. Must implement `Clone`.
21+
///
22+
/// # Memory Management Note
23+
///
24+
/// When referencing `Memo` instances that belong to other struct instances
25+
/// (for example, when one `ViewModel` holds references to memos in another `ViewModel`),
26+
/// you **must** store them as `Weak<Memo<T>>` obtained via `Rc::downgrade` instead of
27+
/// cloning a strong `Rc`. Failing to do so can create reference cycles between the structs
28+
/// and their dependent effects, preventing proper cleanup and causing memory leaks.
2129
///
2230
/// # Examples
2331
///

cache/src/signal.rs

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,14 @@ use crate::{Effect, IMemo, IObservable, effect_stack::EffectStackEntry};
2121
///
2222
/// - `T`: The type of the value stored in the signal. Must implement `Eq`.
2323
///
24+
/// # Memory Management Note
25+
///
26+
/// When referencing `Signal` instances that belong to other struct instances
27+
/// (for example, when one `ViewModel` holds references to signals in another `ViewModel`),
28+
/// you **must** store them as `Weak<Signal<T>>` obtained via `Rc::downgrade` instead of
29+
/// cloning a strong `Rc`. Failing to do so can create reference cycles between the structs
30+
/// and their dependent effects, preventing proper cleanup and causing memory leaks.
31+
///
2432
/// # Examples
2533
///
2634
/// ## Basic usage
@@ -60,8 +68,15 @@ use crate::{Effect, IMemo, IObservable, effect_stack::EffectStackEntry};
6068
/// assert_eq!(*vm.name.get(), "Bob");
6169
/// ```
6270
pub struct Signal<T> {
71+
/// Current value of the signal.
6372
value: RefCell<T>,
73+
74+
/// Memoized computations that depend on this signal.
75+
/// Weak references are used to avoid memory leaks.
6476
dependents: RefCell<Vec<Weak<dyn IMemo>>>,
77+
78+
/// Effects that depend on this signal.
79+
/// Weak references prevent retaining dropped effects.
6580
effects: RefCell<Vec<Weak<Effect>>>,
6681
}
6782

0 commit comments

Comments
 (0)