Function arc_signal
pub fn arc_signal<T>(value: T) -> (ArcReadSignal<T>, ArcWriteSignal<T>)
Expand description
Creates a reference-counted signal.
A signal is a piece of data that may change over time, and notifies other code when it has changed. This is the atomic unit of reactivity, which begins all other processes of updating.
Takes the initial value as an argument, and returns a tuple containing an
ArcReadSignal
and an ArcWriteSignal
.
This returns reference-counted signals, which are Clone
but not Copy
. For arena-allocated
Copy
signals, use signal
.
let (count, set_count) = arc_signal(0);
// ✅ calling the getter clones and returns the value
// this can be `count()` on nightly
assert_eq!(count.get(), 0);
// ✅ calling the setter sets the value
// this can be `set_count(1)` on nightly
set_count.set(1);
assert_eq!(count.get(), 1);
// ❌ you could call the getter within the setter
// set_count.set(count.get() + 1);
// ✅ however it's more efficient to use .update() and mutate the value in place
set_count.update(|count: &mut i32| *count += 1);
assert_eq!(count.get(), 2);
// ✅ you can create "derived signals" with a Fn() -> T interface
let double_count = move || count.get() * 2;
set_count.set(0);
assert_eq!(double_count(), 0);
set_count.set(1);
assert_eq!(double_count(), 2);