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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
use std::{cell::RefCell, iter, rc::Rc};
use crate::api::Liftable;
pub(crate) trait SignalExt<'a> {
fn react(&self);
fn guard(&self) -> SignalGuard<'a>;
fn decrease_dirty(&self);
fn get_dirty(&self) -> isize;
fn clone_box(&self) -> Box<dyn SignalExt<'a> + 'a>;
fn collect_guards_recursive(&self, result: &mut Vec<SignalGuardInner<'a>>);
fn collect_predecessors_recursive(&self, result: &mut Vec<SignalGuardInner<'a>>);
fn reset_explicitly_modified(&self);
}
pub(crate) trait RefStrategy<'a> {
type Ref<T: 'a>: 'a;
fn new_ref<T: 'a>(inner: &Rc<SignalInner<'a, T>>) -> Self::Ref<T>;
fn upgrade<T: 'a>(ref_: &Self::Ref<T>) -> Option<Rc<SignalInner<'a, T>>>;
}
pub(crate) struct WeakRefStrategy;
impl<'a> RefStrategy<'a> for WeakRefStrategy {
type Ref<T: 'a> = std::rc::Weak<SignalInner<'a, T>>;
fn new_ref<T: 'a>(inner: &Rc<SignalInner<'a, T>>) -> Self::Ref<T> {
Rc::downgrade(inner)
}
fn upgrade<T: 'a>(ref_: &Self::Ref<T>) -> Option<Rc<SignalInner<'a, T>>> {
ref_.upgrade()
}
}
pub(crate) struct StrongRefStrategy;
impl<'a> RefStrategy<'a> for StrongRefStrategy {
type Ref<T: 'a> = Rc<SignalInner<'a, T>>;
fn new_ref<T: 'a>(inner: &Rc<SignalInner<'a, T>>) -> Self::Ref<T> {
inner.clone()
}
fn upgrade<T: 'a>(ref_: &Self::Ref<T>) -> Option<Rc<SignalInner<'a, T>>> {
Some(ref_.clone())
}
}
pub(crate) struct WeakSignalRef<'a> {
upgrade: Box<dyn Fn() -> Option<Box<dyn SignalExt<'a> + 'a>> + 'a>,
}
impl<'a> WeakSignalRef<'a> {
pub fn new<T: 'a>(signal: &Signal<'a, T>) -> Self {
let weak = Rc::downgrade(&signal.0);
WeakSignalRef {
upgrade: Box::new(move || {
weak.upgrade()
.map(|rc| Box::new(Signal(rc)) as Box<dyn SignalExt<'a> + 'a>)
}),
}
}
pub fn upgrade(&self) -> Option<Box<dyn SignalExt<'a> + 'a>> {
(self.upgrade)()
}
pub fn is_alive(&self) -> bool {
self.upgrade().is_some()
}
}
/// The inner part of a signal guard
pub struct SignalGuardInner<'a>(Box<dyn SignalExt<'a> + 'a>);
/// Signal guard that triggers reactions on drop
#[allow(dead_code)]
#[allow(unused_must_use)]
pub struct SignalGuard<'a>(Vec<SignalGuardInner<'a>>);
impl<'a> SignalGuard<'a> {
/// Combine two signal guards into one
pub fn and(mut self, mut other: SignalGuard<'a>) -> SignalGuard<'a> {
self.0.append(&mut other.0);
self
}
}
impl<'a> Drop for SignalGuardInner<'a> {
fn drop(&mut self) {
self.0.decrease_dirty();
if self.0.get_dirty() == 0 {
self.0.react();
self.0.reset_explicitly_modified();
}
}
}
impl<'a> Drop for SignalGuard<'a> {
fn drop(&mut self) {
// First drop all inner guards (triggers immediate reactions)
drop(std::mem::take(&mut self.0));
}
}
/// The inner data of a signal
pub struct SignalInner<'a, T> {
pub(crate) value: RefCell<T>,
pub(crate) react_fns: RefCell<Vec<Box<dyn Fn() + 'a>>>,
pub(crate) successors: RefCell<Vec<WeakSignalRef<'a>>>,
pub(crate) predecessors: RefCell<Vec<WeakSignalRef<'a>>>,
pub(crate) dirty: RefCell<isize>,
pub(crate) explicitly_modified: RefCell<bool>,
}
/// Signal representing a reactive value
pub struct Signal<'a, T>(pub(crate) Rc<SignalInner<'a, T>>);
impl<'a, T: 'a> Signal<'a, T> {
/// Create a new signal with the given initial value
pub fn new(initial: T) -> Self {
let inner = Rc::new(SignalInner {
value: RefCell::new(initial),
react_fns: RefCell::new(Vec::new()),
successors: RefCell::new(Vec::new()),
predecessors: RefCell::new(Vec::new()),
dirty: RefCell::new(0),
explicitly_modified: RefCell::new(false),
});
Signal(inner)
}
/// Helper: Temporarily take value without cloning using MaybeUninit
#[inline]
fn take_value<U>(cell: &RefCell<U>) -> U {
let mut temp = unsafe { std::mem::MaybeUninit::<U>::uninit().assume_init() };
std::mem::swap(&mut *cell.borrow_mut(), &mut temp);
temp
}
/// Send a new value to the signal
///
/// This will replace the current value of the signal with the new value.
/// The signals that depend on this signal will be notified and updated accordingly.
///
/// It returns a `SignalGuard` that ensures reactions are processed when dropped and
/// prevents premature reactions during multiple sends. (Batch updates)
/// # Example
/// ```rust
/// let signal = Signal::new(0);
/// signal.send(42); // sets the signal's value to 42
///
/// signal.with(|v| println!("Signal value: {}", v));
/// (signal.send(66), signal.send(100));
/// // sets the signal's value to 100 and prints "Signal value: 100" only once
/// ```
pub fn send(&self, new_value: T) -> SignalGuard<'a> {
self.modify(|v| *v = new_value);
*self.0.explicitly_modified.borrow_mut() = true;
self.guard()
}
/// Send a modification to the signal
///
/// This will apply the provided function to modify the current value of the signal.
/// The signals that depend on this signal will be notified and updated accordingly.
///
/// It returns a `SignalGuard` that ensures reactions are processed when dropped and
/// prevents premature reactions during multiple sends. (Batch updates)
pub fn send_with<F>(&self, f: F) -> SignalGuard<'a>
where
F: FnOnce(&mut T),
{
self.modify(f);
self.guard()
}
pub fn set(&mut self, signal: Signal<'a, T>) {
self.0 = signal.0;
}
/// Map the signal to a new signal
///
/// This creates a new signal that depends on the current signal.
/// Changes to the source signal will propagate to the new signal.
///
/// # Example
/// ```rust
/// let a = Signal::new(10);
/// let b = a.map(|x| x * 2);
/// let _observer = b.map(|x| println!("b changed: {}", x));
/// a.send(5); // prints "b changed: 10"
/// ```
pub fn map<U: 'a, F>(&self, f: F) -> Signal<'a, U>
where
F: Fn(&T) -> U + 'a,
{
self.map_ref::<U, F, WeakRefStrategy>(f)
}
/// Map the signal to a new signal with strong references
///
/// This creates a new signal that depends on the current signal.
/// Changes to the source signal will propagate to the new signal.
/// This mapping uses strong references.
///
/// # Example
/// ```rust
/// let a = Signal::new(10);
/// let b = a.map(|x| x * 2);
/// b.with(|x| println!("b changed: {}", x));
/// a.send(5); // prints "b changed: 10"
/// ```
pub fn with<U: 'a, F>(&self, f: F) -> Signal<'a, U>
where
F: Fn(&T) -> U + 'a,
{
self.map_ref::<U, F, StrongRefStrategy>(f)
}
fn map_ref<U: 'a, F, S: RefStrategy<'a>>(&self, f: F) -> Signal<'a, U>
where
F: Fn(&T) -> U + 'a,
{
let new_signal = Signal::new(f(&self.0.value.borrow()));
let result_new_signal = new_signal.clone();
let new_signal_ref = S::new_ref(&new_signal.0);
let source_ref = S::new_ref(&self.0);
let react_fn = Box::new(move || {
if let Some(new_sig_inner) = S::upgrade(&new_signal_ref) {
if !*new_sig_inner.explicitly_modified.borrow() {
if let Some(src_inner) = S::upgrade(&source_ref) {
let new_value = f(&src_inner.value.borrow());
*new_sig_inner.value.borrow_mut() = new_value;
}
}
}
});
self.0.react_fns.borrow_mut().push(react_fn);
self.0
.successors
.borrow_mut()
.push(WeakSignalRef::new(&new_signal));
result_new_signal
}
/// Map the signal contravariantly to a new signal
///
/// This creates a new signal that the current signal depends on.
/// Changes to the new signal will propagate back to the original signal.
/// It is inspired by the concept of contravariant functors in category theory.
///
/// # Example
/// ```rust
/// let result = Signal::new(42);
/// let source = result.contramap(|x| x * 2);
/// result.with(|x| println!("result changed: {}", x));
/// source.with(|x| println!("source changed: {}", x));
/// source.send(100);
/// // prints "source changed: 100" and "result changed: 50"
/// ```
pub fn contramap<F, U>(&self, f: F) -> Signal<'a, U>
where
F: Fn(&U) -> T + 'a,
U: Default + 'a,
{
let new_signal = Signal::new(U::default());
let result_new_signal = new_signal.clone();
let source_inner = Rc::downgrade(&self.0);
let new_signal_rc = Rc::downgrade(&new_signal.0);
let react_fn = Box::new(move || {
if let Some(new_sig) = new_signal_rc.upgrade() {
if *new_sig.explicitly_modified.borrow() {
let u_value_ref = new_sig.value.borrow();
let t_value = f(&u_value_ref);
drop(u_value_ref);
if let Some(source) = source_inner.upgrade() {
*source.value.borrow_mut() = t_value;
*source.explicitly_modified.borrow_mut() = true;
}
}
}
});
new_signal.0.react_fns.borrow_mut().push(react_fn);
new_signal
.0
.predecessors
.borrow_mut()
.push(WeakSignalRef::new(self));
result_new_signal
}
/// Map the signal bidirectionally to a new signal
///
/// This creates a new signal that depends on the current signal,
/// and the current signal also depends on the new signal.
/// Changes to either signal will propagate to the other signal.
/// It is inspired by the concept of profunctors in category theory.
///
/// # Example
/// ```rust
/// let a = Signal::new(10);
/// let b = a.promap(|x| x * 2, |y| y / 2);
/// a.with(|x| println!("a changed: {}", x));
/// b.with(|x| println!("b changed: {}", x));
/// a.send(5); // prints "a changed: 5" and "b changed: 10"
/// b.send(50); // prints "b changed: 50" and "a changed: 25"
/// ```
pub fn promap<F, G, U>(&self, f: F, g: G) -> Signal<'a, U>
where
F: Fn(&T) -> U + 'a,
G: Fn(&U) -> T + 'a,
U: Default + 'a,
{
let new_signal = Signal::new(U::default());
let result_new_signal = new_signal.clone();
let source_weak = Rc::downgrade(&self.0);
let new_signal_weak = Rc::downgrade(&new_signal.0);
// Forward reaction: T -> U (covariant)
let source_inner = source_weak.clone();
let new_signal_rc = new_signal_weak.clone();
let forward_react_fn = Box::new(move || {
if let Some(new_sig) = new_signal_rc.upgrade() {
if !*new_sig.explicitly_modified.borrow() {
if let Some(source) = source_inner.upgrade() {
let t_value = source.value.borrow();
let u_value = f(&t_value);
drop(t_value);
*new_sig.value.borrow_mut() = u_value;
}
}
}
});
self.0.react_fns.borrow_mut().push(forward_react_fn);
self.0
.successors
.borrow_mut()
.push(WeakSignalRef::new(&new_signal));
// Backward reaction: U -> T (contravariant)
let new_signal_rc_back = new_signal_weak.clone();
let source_inner_back = source_weak.clone();
let backward_react_fn = Box::new(move || {
if let Some(new_sig) = new_signal_rc_back.upgrade() {
if *new_sig.explicitly_modified.borrow() {
let u_value_ref = new_sig.value.borrow();
let t_value = g(&u_value_ref);
drop(u_value_ref);
if let Some(source) = source_inner_back.upgrade() {
*source.value.borrow_mut() = t_value;
*source.explicitly_modified.borrow_mut() = true;
}
}
}
});
new_signal.0.react_fns.borrow_mut().push(backward_react_fn);
// Register self (source) as a predecessor of new_signal (backward dependency)
// When new_signal changes, it propagates backward to self
new_signal
.0
.predecessors
.borrow_mut()
.push(WeakSignalRef::new(self));
result_new_signal
}
/// Combine two signals into one
///
/// This combines two signals into a new signal that holds a tuple of their values.
/// Changes to either signal will propagate to the new combined signal.
///
/// # Example
/// ```rust
/// let a = Signal::new(10);
/// let b = a.map(|x| x * 2);
/// let ab = a.combine(&b);
/// ab.with(|(x, y)| println!("c changed: {} + {} = {}", x, y, x + y));
/// a.send(5); // prints "c changed: 5 + 10 = 15"
/// ```
pub fn combine<S>(&self, another: S) -> Signal<'a, (T, S::Inner)>
where
S: Liftable<'a>,
S::Inner: 'a,
T: 'a,
{
self.combine_ref::<S, WeakRefStrategy>(another)
}
/// Combine two signals into one with strong references
///
/// This combines two signals into a new signal that holds a tuple of their values.
/// Changes to either signal will propagate to the new combined signal.
/// This combination uses strong references.
///
/// # Example
/// ```rust
/// let a = Signal::new(10);
/// let b = a.map(|x| x * 2);
/// a.and(&b).with(|(x, y)| println!("c changed: {} + {} = {}", x, y, x + y));
/// a.send(5); // prints "c changed: 5 + 10 = 15"
/// ```
pub fn and<S>(&self, another: S) -> Signal<'a, (T, S::Inner)>
where
S: Liftable<'a>,
S::Inner: 'a,
T: 'a,
{
self.combine_ref::<S, StrongRefStrategy>(another)
}
fn combine_ref<S: Liftable<'a>, Strat: RefStrategy<'a>>(
&self,
another: S,
) -> Signal<'a, (T, S::Inner)>
where
S::Inner: 'a,
T: 'a,
{
let another = another.as_ref();
// Take values temporarily, create signal, restore values
let temp_val_0 = Self::take_value(&self.0.value);
let temp_val_1 = Self::take_value(&another.0.value);
let new_signal = Signal::new((temp_val_0, temp_val_1));
std::mem::swap(
&mut *self.0.value.borrow_mut(),
&mut new_signal.0.value.borrow_mut().0,
);
std::mem::swap(
&mut *another.0.value.borrow_mut(),
&mut new_signal.0.value.borrow_mut().1,
);
let result_new_signal = new_signal.clone();
// Register reaction for first source
let new_signal_ref = Strat::new_ref(&new_signal.0);
let self_ref = Strat::new_ref(&self.0);
let react_fn_self = Box::new(move || {
if let (Some(new_sig), Some(src)) =
(Strat::upgrade(&new_signal_ref), Strat::upgrade(&self_ref))
{
if !*new_sig.explicitly_modified.borrow() {
std::mem::swap(
&mut *src.value.borrow_mut(),
&mut new_sig.value.borrow_mut().0,
);
}
}
});
self.0.react_fns.borrow_mut().push(react_fn_self);
self.0
.successors
.borrow_mut()
.push(WeakSignalRef::new(&result_new_signal));
// Register reaction for second source
let new_signal_ref_2 = Strat::new_ref(&new_signal.0);
let another_ref = Strat::new_ref(&another.0);
let react_fn_another = Box::new(move || {
if let (Some(new_sig), Some(src)) = (
Strat::upgrade(&new_signal_ref_2),
Strat::upgrade(&another_ref),
) {
if !*new_sig.explicitly_modified.borrow() {
std::mem::swap(
&mut *src.value.borrow_mut(),
&mut new_sig.value.borrow_mut().1,
);
}
}
});
another.0.react_fns.borrow_mut().push(react_fn_another);
another
.0
.successors
.borrow_mut()
.push(WeakSignalRef::new(&result_new_signal));
result_new_signal
}
/// Extend the signal with a vector of signals
///
/// This creates a new signal that depends on the current signal and the provided signals.
/// Changes to any of the source signals will propagate to the new signal.
///
/// # Example
/// ```rust
/// let a = Signal::new(1);
/// let b = Signal::new(2);
/// let c = Signal::new(3);
/// let d = a.extend(vec![b, c]);
/// d.with(|values| println!("d changed: {:?}", values));
/// a.send(10); // prints "d changed: [10, 2, 3]"
/// (b.send(20), c.send(30)); // prints "d changed: [10, 20, 30]"
/// ```
pub fn extend<S>(&self, others: impl IntoIterator<Item = S>) -> Signal<'a, Vec<T>>
where
S: Liftable<'a, Inner = T>,
T: 'a,
{
self.extend_ref::<S, WeakRefStrategy>(others)
}
/// Extend the signal with a vector of signals with strong references
///
/// This creates a new signal that depends on the current signal and the provided signals.
/// Changes to any of the source signals will propagate to the new signal.
/// It uses strong references.
///
/// # Example
/// ```rust
/// let a = Signal::new(1);
/// let b = Signal::new(2);
/// let c = Signal::new(3);
/// a.follow(vec![b, c]).with(|values| println!("d changed: {:?}", values));
/// a.send(10); // prints "d changed: [10, 2, 3]"
/// (b.send(20), c.send(30)); // prints "d changed: [10, 20, 30]"
/// ```
pub fn follow<S>(&self, others: impl IntoIterator<Item = S>) -> Signal<'a, Vec<T>>
where
S: Liftable<'a, Inner = T>,
T: 'a,
{
self.extend_ref::<S, StrongRefStrategy>(others)
}
fn extend_ref<S, Strat: RefStrategy<'a>>(
&self,
others: impl IntoIterator<Item = S>,
) -> Signal<'a, Vec<T>>
where
S: Liftable<'a, Inner = T>,
T: 'a,
{
let others_signals: Vec<Signal<'a, T>> =
others.into_iter().map(|s| s.as_ref().clone()).collect();
// Collect values using take_value helper - no cloning!
let all_signals: Vec<&Signal<'a, T>> =
iter::once(self).chain(others_signals.iter()).collect();
let temp_values: Vec<T> = all_signals
.iter()
.map(|s| Self::take_value(&s.0.value))
.collect();
let new_signal: Signal<'a, Vec<T>> = Signal::new(temp_values);
// Restore original values by swapping back
for (index, signal) in all_signals.iter().enumerate() {
std::mem::swap(
&mut *signal.0.value.borrow_mut(),
&mut new_signal.0.value.borrow_mut()[index],
);
}
let result_new_signal = new_signal.clone();
iter::once(self)
.chain(others_signals.iter())
.enumerate()
.for_each(|(index, signal)| {
let new_signal_ref = Strat::new_ref(&new_signal.0);
let source_ref = Strat::new_ref(&signal.0);
let react_fn = Box::new(move || {
if let Some(new_sig) = Strat::upgrade(&new_signal_ref) {
if !*new_sig.explicitly_modified.borrow() {
if let Some(src) = Strat::upgrade(&source_ref) {
// Swap values instead of cloning (during reaction only)
std::mem::swap(
&mut new_sig.value.borrow_mut()[index],
&mut *src.value.borrow_mut(),
);
}
}
}
});
signal.0.react_fns.borrow_mut().push(react_fn);
signal
.0
.successors
.borrow_mut()
.push(WeakSignalRef::new(&new_signal));
});
result_new_signal
}
/// Let this signal depend on another signal
///
/// This synchronizes the value of this signal with the value of the dependency signal.
/// Whenever the dependency signal changes, this signal will be updated to match its value.
///
/// The returned signal is exactly the argument `dependency`. You can break the dependency chain
/// by dropping the returned signal if `dependency` is weakly referenced.
///
/// # Example
/// ```rust
/// let a = Signal::new(1);
/// let mut b = Signal::new(2);
/// b = a.depend(b);
/// a.with(|v| println!("a changed: {}", v));
/// b.send(3); // prints "a changed: 3"
/// ```
///
/// The example above is analogous to:
/// ```rust
/// let a = Signal::new(1);
/// let b = a.map(|v| *v);
/// b.with(|v| println!("b changed: {}", v));
/// a.send(3); // prints "b changed: 3"
/// ```
pub fn depend(&self, dependency: Signal<'a, T>) -> Signal<'a, T>
where
T: Clone,
{
let self_weak = Rc::downgrade(&self.0);
let dependency_weak = Rc::downgrade(&dependency.0);
let react_fn = Box::new(move || {
if let Some(dep) = dependency_weak.upgrade() {
if let Some(target) = self_weak.upgrade() {
if !*target.explicitly_modified.borrow() {
// Swap values instead of cloning (during reaction only)
std::mem::swap(
&mut *target.value.borrow_mut(),
&mut *dep.value.borrow_mut(),
);
}
}
}
});
dependency.0.react_fns.borrow_mut().push(react_fn);
dependency
.0
.successors
.borrow_mut()
.push(WeakSignalRef::new(self));
dependency
}
pub(crate) fn modify(&self, f: impl FnOnce(&mut T)) {
let mut value = self.0.value.borrow_mut();
f(&mut value);
}
fn mark_dirty(&self) {
*self.0.dirty.borrow_mut() += 1;
}
fn collect_and_iterate<F>(&self, refs: &RefCell<Vec<WeakSignalRef<'a>>>, mut callback: F)
where
F: FnMut(&dyn SignalExt<'a>),
{
refs.borrow_mut().retain(|s| s.is_alive());
for s in refs.borrow().iter() {
if let Some(signal) = s.upgrade() {
callback(&*signal);
}
}
}
fn collect_guards(&self, result: &mut Vec<SignalGuardInner<'a>>) {
self.mark_dirty();
result.push(SignalGuardInner(self.clone_box()));
self.collect_and_iterate(&self.0.successors, |signal| {
signal.collect_guards_recursive(result);
});
self.collect_and_iterate(&self.0.predecessors, |signal| {
signal.collect_predecessors_recursive(result);
});
}
/// Lift an array of liftable items into a signal of an array
///
/// This creates a new signal that depends on the provided liftable items.
/// Changes to any of the source signals will propagate to the new signal.
///
/// # Example
/// ```rust
/// let a = Signal::new(1);
/// let b = Signal::new(2);
/// let c = Signal::new(3);
/// let abc = Signal::lift_from_array([a, b, c]);
/// abc.with(|values| println!("abc changed: {:?}", values));
/// (a.send(10), b.send(20), c.send(30)); // prints "abc changed: [10, 20, 30]"
/// ```
pub fn lift_from_array<S, const N: usize>(items: [S; N]) -> Signal<'a, [S::Inner; N]>
where
S: Liftable<'a>,
S::Inner: 'a,
{
let signals: [Signal<'a, S::Inner>; N] = std::array::from_fn(|i| items[i].as_ref().clone());
// Take values using helper - no cloning!
let initial: [S::Inner; N] = std::array::from_fn(|i| Self::take_value(&signals[i].0.value));
let new_signal: Signal<'a, [S::Inner; N]> = Signal::new(initial);
// Restore original values by swapping back
for (index, signal) in signals.iter().enumerate() {
std::mem::swap(
&mut *signal.0.value.borrow_mut(),
&mut new_signal.0.value.borrow_mut()[index],
);
}
let result_new_signal = new_signal.clone();
for (index, signal) in signals.iter().enumerate() {
let new_signal_weak = Rc::downgrade(&new_signal.0);
let source_for_closure = Rc::downgrade(&signal.0);
let react_fn = Box::new(move || {
if let Some(new_sig) = new_signal_weak.upgrade() {
if !*new_sig.explicitly_modified.borrow() {
if let Some(source) = source_for_closure.upgrade() {
// Swap instead of cloning (during reaction only)
std::mem::swap(
&mut new_sig.value.borrow_mut()[index],
&mut *source.value.borrow_mut(),
);
}
}
}
});
signal.0.react_fns.borrow_mut().push(react_fn);
signal
.0
.successors
.borrow_mut()
.push(WeakSignalRef::new(&new_signal));
}
result_new_signal
}
}
impl<'a, T: 'a> SignalExt<'a> for Signal<'a, T> {
fn react(&self) {
self.0.react_fns.borrow().iter().for_each(|react_fn| {
react_fn();
});
}
fn guard(&self) -> SignalGuard<'a> {
let mut result = vec![];
self.collect_guards(&mut result);
SignalGuard(result)
}
fn clone_box(&self) -> Box<dyn SignalExt<'a> + 'a> {
Box::new(Signal(Rc::clone(&self.0)))
}
fn decrease_dirty(&self) {
*self.0.dirty.borrow_mut() -= 1;
}
fn get_dirty(&self) -> isize {
*self.0.dirty.borrow()
}
fn reset_explicitly_modified(&self) {
*self.0.explicitly_modified.borrow_mut() = false;
}
fn collect_guards_recursive(&self, result: &mut Vec<SignalGuardInner<'a>>) {
self.mark_dirty();
result.push(SignalGuardInner(self.clone_box()));
self.collect_and_iterate(&self.0.successors, |signal| {
signal.collect_guards_recursive(result);
});
}
fn collect_predecessors_recursive(&self, result: &mut Vec<SignalGuardInner<'a>>) {
self.mark_dirty();
result.push(SignalGuardInner(self.clone_box()));
// Collect predecessors last so they drop last (react last)
self.collect_and_iterate(&self.0.predecessors, |signal| {
signal.collect_predecessors_recursive(result);
});
}
}
impl<T> Clone for Signal<'_, T> {
fn clone(&self) -> Self {
Self(self.0.clone())
}
}
impl<'a, T> AsRef<Signal<'a, T>> for Signal<'a, T> {
fn as_ref(&self) -> &Signal<'a, T> {
self
}
}
#[cfg(test)]
mod tests {
use crate::api::LiftInto;
use super::*;
#[test]
fn test_signal() {
let a = Signal::new(0);
let _a = a.map(|x| println!("a changed: {}", x));
(a.send(100), a.send(5));
}
#[test]
fn test_signal1() {
let a = Signal::new(0);
let b = a.map(|x| x * 2);
let _b = b.map(|x| println!("b changed: {}", x));
drop(b);
a.send(100);
}
#[test]
fn test_signal2() {
let a = Signal::new(0);
let b = a.map(|x| x * 2);
let ab = a.combine(&b);
let _ab = ab.map(|(x, y)| println!("c changed: {} + {} = {}", x, y, x + y));
(a.send(5), a.send(100));
}
#[test]
fn test_signal3() {
let a = Signal::new(0);
let b = a.map(|x| x * 2);
let ab = (&a, &b).lift();
let _ab = ab.map(|(x, y)| println!("c changed: {} + {} = {}", x, y, x + y));
(a.send(5), b.send(100));
}
#[test]
fn test_signal4() {
let a = Signal::new(0);
let b = Signal::new(10);
let c = Signal::new(20);
let abc = [&a, &b, &c].lift();
let _abc =
abc.map(|[x, y, z]| println!("d changed: {} + {} + {} = {}", x, y, z, x + y + z));
let d = Signal::new(0);
let abcd = abc.combine(&d);
let _abcd = abcd.map(|numbers| {
println!(
"e changed: {} + {} + {} + {} = {}",
numbers.0[0],
numbers.0[1],
numbers.0[2],
numbers.1,
numbers.0.iter().sum::<i32>() + numbers.1
)
});
(a.send(5), b.send(15), c.send(25), abc.send([2, 3, 4]));
}
#[test]
fn test_signal5() {
let result = Signal::new(42);
let source1 = result.contramap(|x| x + 1);
let source2 = source1.contramap(|x| x * 2);
let _observer_1 = result.map(|x| println!("result changed: {}", x));
let _observer_2 = source1.map(|x| println!("source1 changed: {}", x));
let _observer_3 = source2.map(|x| println!("source2 changed: {}", x));
println!("--- Sending to source1 ---");
source1.send(100);
println!("--- Sending to source2 ---");
source2.send(200);
println!("--- Sending to source1 and source2 ---");
(source1.send(300), source2.send(400));
}
#[test]
fn test_promap_forward() {
let source = Signal::new(10);
let derived = source.promap(|x| x * 2, |y| y / 2);
let _ = derived.map(|x| println!("derived changed: {}", x));
source.send(5);
}
#[test]
fn test_promap_backward() {
let source = Signal::new(10);
let derived = source.promap(|x| x * 2, |y| y / 2);
let _ = source.map(|x| println!("source changed: {}", x));
let _ = derived.map(|x| println!("derived changed: {}", x));
derived.send(50);
}
#[test]
fn test_promap_bidirectional() {
let a = Signal::new(10);
let b = a.promap(|x| x * 2, |y| y / 2);
let c = b.promap(|x| x + 3, |y| y - 3);
let _observer_a = a.map(|x| println!("a changed: {}", x));
let _observer_b = b.map(|x| println!("b changed: {}", x));
let _observer_c = c.map(|x| println!("c changed: {}", x));
println!("--- Sending to a ---");
a.send(5);
println!("--- Sending to c ---");
c.send(13);
println!("--- Sending to b ---");
b.send(10);
println!("--- Sending to a and c ---");
a.send(20).and(c.send(50));
println!("--- Sending to b and c ---");
(b.send(30), c.send(60));
}
#[test]
fn test_high_order_signal() {
let source = Signal::new(0);
let derived = source.map(|x| Signal::new(x + 1));
let _ = derived.map(|s| s.send(233));
let _ = derived.map(|s| s.map(|x| println!("derived changed: {}", x)));
source.send(5);
}
#[test]
fn test_depend() {
let a = Signal::new(10);
let b = Signal::new(10);
let c = Signal::new(10);
let _observer_a = a.map(|x| println!("a changed: {}", x));
let _observer_b = b.map(|x| println!("b changed: {}", x));
let _observer_c = c.map(|x| println!("c changed: {}", x));
c.depend(b.with(|x| x * 2));
b.depend(a.clone());
a.send(42);
}
#[test]
fn test_depend2() {
let a = Signal::new(10);
let b = a.map(|x| *x);
let c = b.map(|x| *x);
let _observer_a = a.map(|x| println!("a changed: {}", x));
let _observer_b = b.map(|x| println!("b changed: {}", x));
let _observer_c = c.map(|x| println!("c changed: {}", x));
(a.send(42), b.send(88));
}
}