flo_binding 3.0.0

Declarative binding library for Rust
Documentation
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
//!
//! # `flo_binding`, a data-driven binding library
//!
//! `flo_binding` provides a way to create 'data bindings', which are a way to store
//! and share state between different parts of an application. Applications designed
//! around these data structures are sometimes referred to as 'reactive' applications.
//! 
//! A basic binding can be created using the `bind()` function:
//! 
//! ```
//! # use flo_binding::*;
//!     let binding = bind(1);
//! ```
//! 
//! This can be updated by calling `set()` and retrieved using `get()`:
//! 
//! ```
//! # use flo_binding::*;
//! # let binding = bind(1);
//!     let value = binding.get(); // == 1
//! # assert!(value == 1);
//!     binding.set(2);
//!     let value = binding.get(); // == 2
//! # assert!(value == 2);
//! ```
//! 
//! Cloning a binding will share the state:
//! 
//! ```
//! # use flo_binding::*;
//! # let binding = bind(1);
//!     let another_binding = binding.clone();
//!     another_binding.set(3);
//!     let value = another_binding.get();  // == 3
//! # assert!(value == 3);
//!     let value = binding.get();          // Also == 3
//! # assert!(value == 3);
//! ```
//! 
//! There are two main ways to be notified when a binding has changed. The 
//! `when_changed()` function provides a way to call a function whenever a binding
//! has changed since it was last read, and the `follow()` function will return a 
//! Stream of the most recent value attached to the binding. The streaming approach
//! is the most flexible.
//! 
//! ```
//! # use flo_binding::*;
//! # use futures::prelude::*;
//! # use futures::executor;
//! # executor::block_on(async {
//!     let binding             = bind(1);
//!     let mut event_lifetime  = binding.when_changed(notify(|| { println!("Binding changed"); }));
//!     let mut binding_stream  = follow(binding.clone());
//! 
//!     let value = binding_stream.next().await;        // == 1
//! # assert!(value == Some(1));
//!     binding.set(2);                                 // Prints 'Binding changed'
//!     binding.set(3);                                 // Changed flag is set, so prints nothing
//!     let value = binding.get();                      // == 3
//! # assert!(value == 3);
//! 
//!     binding.set(4);                                 // Prints 'Binding changed' again
//!     let value = binding_stream.next().await;        // == 4 (stream does not return intermediate values)
//! # assert!(value == Some(4));
//! # binding.set(5);
//!     let value = binding_stream.next().await;        // Blocks until something elsewhere updates the binding
//! # assert!(value == Some(5));
//! 
//!     event_lifetime.done();
//!     binding.set(5);                                 // Prints nothing as the 'when_changed' event has been deregistered
//! # });
//! ```
//! 
//! The inverse of `follow()` is `bind_stream()`, which creates a bindings that is kept
//! up to date with whatever the last value received from a stream is:
//! 
//! ```
//! # use flo_binding::*;
//!     let binding             = bind(1);
//!     let binding_from_stream = bind_stream(follow(binding.clone()), 1, |_old_value, new_value| new_value);
//! 
//!     let value = binding.get();                  // == 1
//!     let value = binding_from_stream.get();      // == 1
//! 
//!     binding.set(2);
//!     let value = binding_from_stream.get();      // == 2
//! ```
//! 
//! A stream binding like this is read-only, but is a good way to convert any stream of
//! state values into a value representing a static state. It implements all of the other
//! binding operations.
//! 
//! Another important type of binding is the `computed()` binding, which makes it possible 
//! to create a binding that derives a value from other bindings. Computed bindings 
//! automatically monitor any bindings that were captured for changes, so they can be
//! `follow`ed or `when_change`d as with any other binding:
//! 
//! ```
//! # use flo_binding::*;
//!     let binding         = bind(1);
//!     let binding_copy    = binding.clone();
//!     let one_more        = computed(move || binding_copy.get() + 1);
//! 
//!     let event_lifetime  = one_more.when_changed(notify(|| println!("Computed binding changed")));
//! 
//!     let value = one_more.get();     // == 2 (1 + 1)
//!     binding.set(2);                 // Prints 'Computed binding changed'
//!     binding.set(3);                 // Computed binding has not been read since the last notification so prints nothing
//!     let value = one_more.get();     // == 4 (3 + 1)
//! ```
//! 
//! For collections of data, `flo_binding` uses the concept of a 'rope binding'. The 
//! general rope data type is provided by the [`flo_rope`](https://crates.io/crates/flo_rope)
//! crate. These bindings send differences rather than their full state when streaming and
//! are internally represented by a data structure that can perform deletions and insertions
//! efficiently. Unlike the traditional concept of a rope, they aren't limited to editing
//! strings, and can annotate their contents with attributes, which makes them suitable for
//! representing sequences of any kind, or sequences of rich text annotated with style
//! information.
//! 
//! ```
//! # use flo_binding::*;
//! # use futures::prelude::*;
//! # use futures::executor;
//! # executor::block_on(async {
//!     let mutable_rope        = RopeBindingMut::<usize, ()>::new();
//!     let rope_copy           = RopeBinding::from_stream(mutable_rope.follow_changes());
//!     let mut rope_stream     = rope_copy.follow_changes();
//! 
//!     mutable_rope.replace(0..0, vec![1, 2, 3, 4]);
//! 
//!     let next            = rope_stream.next().await;                         // == RopeAction::Replace(0..0, vec![1,2,3,4]))
//! 
//!     let rope_len        = rope_copy.len();                                  // == 4
//!     let rope_content    = rope_copy.read_cells(0..4).collect::<Vec<_>>();   // == vec![1, 2, 3, 4]
//! # });
//! ```
//! 
//! The `flo_rope` library provides some extra functionality - for example, a way to create the
//! `RopeAction`s for a rope by using a diff algorithm on a changing sequence instead of just
//! reporting the changes as they arrive.
//! 
//! ## Companion libraries
//! 
//! Aside from `flo_rope`, the [`desync`](https://crates.io/crates/desync) crate provides a 
//! novel approach to asynchronous code, including pipe operations that work very well with 
//! the streamed updates from the `follow()` function.
//! 
//! The [`flo_stream`](https://crates.io/crates/flo_stream) provides a pubsub system that
//! provides more flexible ways for distributing state through streams.
//! 
//! [`flo_scene`](https://github.com/logicalshift/flo_scene) is a runtime for building
//! complex systems out of entities that exchange messages with each other. It uses
//! `flo_binding` as an ergonomic way to exchange state information.
//!

#![warn(bare_trait_objects)]

mod traits;
pub mod binding_context;
mod binding;
mod computed;
mod bindref;
mod notify_fn;
pub mod releasable;
mod watcher;
mod map_binding;
mod ext;
#[cfg(feature = "stream")]
mod follow;
#[cfg(feature = "stream")]
mod bind_stream;
#[cfg(feature = "rope")]
mod rope_binding;

pub use self::traits::*;
pub use self::binding::*;
pub use self::computed::*;
pub use self::bindref::*;
pub use self::notify_fn::*;
pub use self::watcher::*;
pub use self::map_binding::*;
#[cfg(feature = "stream")]
pub use self::follow::*;
#[cfg(feature = "stream")]
pub use self::bind_stream::*;
#[cfg(feature = "rope")]
pub use self::rope_binding::*;

///
/// Creates a simple bound value with the specified initial value
///
pub fn bind<Value>(val: Value) -> Binding<Value>
where
    Value: Clone + PartialEq,
{
    Binding::new(val)
}

///
/// Creates a computed value that tracks bindings accessed during the function call and marks itself as changed when any of these dependencies also change
///
pub fn computed<Value, TFn>(calculate_value: TFn) -> ComputedBinding<Value, TFn>
where 
    Value:  Clone + Send, 
    TFn:    'static + Send + Sync + Fn() -> Value,
{
    ComputedBinding::new(calculate_value)
}

#[cfg(test)]
mod test {
    use super::*;
    use super::binding_context::*;

    use std::thread;
    use std::sync::*;
    use std::time::Duration;

    #[test]
    fn can_create_binding() {
        let bound = bind(1);
        assert!(bound.get() == 1);
    }

    #[test]
    fn can_update_binding() {
        let bound = bind(1);

        bound.set(2);
        assert!(bound.get() == 2);
    }

    #[test]
    fn notified_on_change() {
        let bound       = bind(1);
        let changed     = bind(false);

        let notify_changed = changed.clone();
        bound.when_changed(notify(move || notify_changed.set(true))).keep_alive();

        assert!(changed.get() == false);
        bound.set(2);
        assert!(changed.get() == true);
    }

    #[test]
    fn not_notified_on_no_change() {
        let bound       = bind(1);
        let changed     = bind(false);

        let notify_changed = changed.clone();
        bound.when_changed(notify(move || notify_changed.set(true))).keep_alive();

        assert!(changed.get() == false);
        bound.set(1);
        assert!(changed.get() == false);
    }

    #[test]
    fn notifies_after_each_change() {
        let bound           = bind(1);
        let change_count    = bind(0);

        let notify_count    = change_count.clone();
        bound.when_changed(notify(move || { let count = notify_count.get(); notify_count.set(count+1) })).keep_alive();

        assert!(change_count.get() == 0);
        bound.set(2);
        assert!(change_count.get() == 1);

        bound.set(3);
        assert!(change_count.get() == 2);

        bound.set(4);
        assert!(change_count.get() == 3);
    }

    #[test]
    fn watcher_notifies_after_get() {
        let bound           = bind(1);
        let change_count    = bind(0);

        let notify_count    = change_count.clone();
        let watcher         = bound.watch(notify(move || { let count = notify_count.get(); notify_count.set(count+1) }));

        assert!(change_count.get() == 0);
        bound.set(2);
        assert!(change_count.get() == 0);

        watcher.get();
        bound.set(3);
        assert!(change_count.get() == 1);

        bound.set(4);
        assert!(change_count.get() == 1);

        bound.set(5);
        assert!(change_count.get() == 1);

        watcher.get();
        bound.set(6);
        assert!(change_count.get() == 2);
    }

    #[test]
    fn watcher_does_not_notify_for_other_watchers() {
        let bound           = bind(1);
        let change_count    = bind(0);

        let notify_count    = change_count.clone();
        let watcher         = bound.watch(notify(move || { let count = notify_count.get(); notify_count.set(count+1) }));
        let other_watcher   = bound.watch(notify(move || { }));

        assert!(change_count.get() == 0);
        bound.set(2);
        assert!(change_count.get() == 0);

        other_watcher.get();
        bound.set(3);
        assert!(change_count.get() == 0);

        bound.set(4);
        assert!(change_count.get() == 0);

        bound.set(5);
        assert!(change_count.get() == 0);

        watcher.get();
        bound.set(6);
        assert!(change_count.get() == 1);
    }

    #[test]
    fn dispatches_multiple_notifications() {
        let bound           = bind(1);
        let change_count    = bind(0);

        let notify_count    = change_count.clone();
        let notify_count2   = change_count.clone();
        bound.when_changed(notify(move || { let count = notify_count.get(); notify_count.set(count+1) })).keep_alive();
        bound.when_changed(notify(move || { let count = notify_count2.get(); notify_count2.set(count+1) })).keep_alive();

        assert!(change_count.get() == 0);
        bound.set(2);
        assert!(change_count.get() == 2);

        bound.set(3);
        assert!(change_count.get() == 4);

        bound.set(4);
        assert!(change_count.get() == 6);
    }

    #[test]
    fn stops_notifying_after_release() {
        let bound           = bind(1);
        let change_count    = bind(0);

        let notify_count = change_count.clone();
        let mut lifetime = bound.when_changed(notify(move || { let count = notify_count.get(); notify_count.set(count+1) }));

        assert!(change_count.get() == 0);
        bound.set(2);
        assert!(change_count.get() == 1);

        lifetime.done();
        assert!(change_count.get() == 1);
        bound.set(3);
        assert!(change_count.get() == 1);
    }

    #[test]
    fn release_only_affects_one_notification() {
        let bound           = bind(1);
        let change_count    = bind(0);

        let notify_count    = change_count.clone();
        let notify_count2   = change_count.clone();
        let mut lifetime    = bound.when_changed(notify(move || { let count = notify_count.get(); notify_count.set(count+1) }));
        bound.when_changed(notify(move || { let count = notify_count2.get(); notify_count2.set(count+1) })).keep_alive();

        assert!(change_count.get() == 0);
        bound.set(2);
        assert!(change_count.get() == 2);

        bound.set(3);
        assert!(change_count.get() == 4);

        bound.set(4);
        assert!(change_count.get() == 6);

        lifetime.done();

        bound.set(5);
        assert!(change_count.get() == 7);

        bound.set(6);
        assert!(change_count.get() == 8);

        bound.set(7);
        assert!(change_count.get() == 9);
    }

    #[test]
    fn binding_context_is_notified() {
        let bound = bind(1);

        bound.set(2);

        let (value, context) = BindingContext::bind(|| bound.get());
        assert!(value == 2);

        let changed = bind(false);
        let notify_changed = changed.clone();
        context.when_changed(notify(move || notify_changed.set(true))).keep_alive();

        assert!(changed.get() == false);
        bound.set(3);
        assert!(changed.get() == true);
    }

    #[test]
    fn can_compute_value() {
        let bound           = bind(1);

        let computed_from   = bound.clone();
        let computed        = computed(move || computed_from.get() + 1);

        assert!(computed.get() == 2);
    }

    #[test]
    fn can_recompute_value() {
        let bound           = bind(1);

        let computed_from   = bound.clone();
        let computed        = computed(move || computed_from.get() + 1);

        assert!(computed.get() == 2);

        bound.set(2);
        assert!(computed.get() == 3);

        bound.set(3);
        assert!(computed.get() == 4);
    }

    #[test]
    fn map_binding_value() {
        let bound           = bind(1);
        let mapped          = bound.map_binding(|val| val + 1);

        assert!(mapped.get() == 2);

        bound.set(2);
        assert!(mapped.get() == 3);

        bound.set(3);
        assert!(mapped.get() == 4);
    }

    #[test]
    fn watch_mapped_bindings() {
        let bound           = bind(1);
        let mapped          = bound.map_binding(|val| val + 1);

        let change_count    = bind(0);
        let change_counter  = change_count.clone();
        let watcher         = mapped.watch(notify(move || change_counter.set(change_counter.get() + 1)));

        assert!(watcher.get() == 2);

        bound.set(2);
        assert!(watcher.get() == 3);
        assert!(change_count.get() == 1);

        bound.set(3);
        assert!(watcher.get() == 4);
        assert!(change_count.get() == 2);
    }


    #[test]
    fn can_recursively_compute_values() {
        let bound               = bind(1);

        let computed_from       = bound.clone();
        let computed_val        = computed(move || computed_from.get() + 1);

        let more_computed_from  = computed_val.clone();
        let more_computed       = computed(move || more_computed_from.get() + 1);

        assert!(computed_val.get() == 2);
        assert!(more_computed.get() == 3);

        bound.set(2);
        assert!(computed_val.get() == 3);
        assert!(more_computed.get() == 4);

        bound.set(3);
        assert!(computed_val.get() == 4);
        assert!(more_computed.get() == 5);
    }

    #[test]
    fn can_recursively_compute_values_2() {
        let bound               = bind(1);

        let computed_from       = bound.clone();
        let computed_val        = computed(move || computed_from.get() + 1);
        let more_computed       = computed(move || computed_val.get() + 1);

        assert!(more_computed.get() == 3);

        bound.set(2);
        assert!(more_computed.get() == 4);

        bound.set(3);
        assert!(more_computed.get() == 5);
    }

    #[test]
    fn can_recursively_compute_values_3() {
        let bound               = bind(1);

        let computed_from       = bound.clone();
        let computed_val        = computed(move || computed_from.get() + 1);
        let more_computed       = computed(move || computed_val.get() + 1);
        let even_more_computed  = computed(move || more_computed.get() + 1);

        assert!(even_more_computed.get() == 4);

        bound.set(2);
        assert!(even_more_computed.get() == 5);

        bound.set(3);
        assert!(even_more_computed.get() == 6);
    }

    #[test]
    #[should_panic]
    fn panics_if_computed_generated_during_binding() {
        let bound               = bind(1);

        let computed_from       = bound.clone();
        let computed_val        = computed(move || computed_from.get() + 1);
        let even_more_computed  = computed(move || {
            let computed_val = computed_val.clone();

            // This computed binding would be dropped after the first evaluation, which would result in the binding never updating.
            // We should panic here.
            let more_computed = computed(move || computed_val.get() + 1);
            more_computed.get() + 1
        });

        assert!(even_more_computed.get() == 4);

        bound.set(2);
        assert!(even_more_computed.get() == 5);

        bound.set(3);
        assert!(even_more_computed.get() == 6);
    }

    #[test]
    fn computed_only_recomputes_as_needed() {
        let bound               = bind(1);

        let counter             = Arc::new(Mutex::new(0));
        let compute_counter     = counter.clone();
        let computed_from       = bound.clone();
        let computed            = computed(move || {
            let mut counter = compute_counter.lock().unwrap();
            *counter = *counter + 1;

            computed_from.get() + 1
        });

        assert!(computed.get() == 2);
        {
            let counter = counter.lock().unwrap();
            assert!(counter.clone() == 1);
        }

        assert!(computed.get() == 2);
        {
            let counter = counter.lock().unwrap();
            assert!(counter.clone() == 1);
        }

        bound.set(2);
        assert!(computed.get() == 3);
        {
            let counter = counter.lock().unwrap();
            assert!(counter.clone() == 2);
        }
    }

    #[test]
    fn computed_caches_values() {
        let update_count            = Arc::new(Mutex::new(0));
        let bound                   = bind(1);

        let computed_update_count   = Arc::clone(&update_count);
        let computed_from           = bound.clone();
        let computed                = computed(move || {
            let mut computed_update_count = computed_update_count.lock().unwrap();
            *computed_update_count += 1;

            computed_from.get() + 1
        });

        assert!(computed.get() == 2);
        assert!(*update_count.lock().unwrap() == 1);

        assert!(computed.get() == 2);
        assert!(*update_count.lock().unwrap() == 1);

        bound.set(2);
        assert!(computed.get() == 3);
        assert!(*update_count.lock().unwrap() == 2);

        bound.set(3);
        assert!(*update_count.lock().unwrap() == 2);
        assert!(computed.get() == 4);
        assert!(*update_count.lock().unwrap() == 3);
    }

    #[test]
    fn computed_notifies_of_changes() {
        let bound           = bind(1);

        let computed_from   = bound.clone();
        let computed        = computed(move || computed_from.get() + 1);

        let changed         = bind(false);
        let notify_changed  = changed.clone();
        computed.when_changed(notify(move || notify_changed.set(true))).keep_alive();

        assert!(computed.get() == 2);
        assert!(changed.get() == false);

        bound.set(2);
        assert!(changed.get() == true);
        assert!(computed.get() == 3);

        changed.set(false);
        bound.set(3);
        assert!(changed.get() == true);
        assert!(computed.get() == 4);
    }

    #[test]
    fn computed_watcher() {
        let bound           = bind(1);

        let computed_from   = bound.clone();
        let computed        = computed(move || computed_from.get() + 1);

        let changed         = bind(false);
        let notify_changed  = changed.clone();
        let watcher         = computed.watch(notify(move || notify_changed.set(true)));

        assert!(watcher.get() == 2);
        assert!(changed.get() == false);

        bound.set(2);
        assert!(changed.get() == true);
        assert!(watcher.get() == 3);

        changed.set(false);
        bound.set(3);
        assert!(changed.get() == true);
        assert!(watcher.get() == 4);
    }

    #[test]
    fn computed_switches_dependencies() {
        let switch          = bind(false);
        let val1            = bind(1);
        let val2            = bind(2);

        let computed_switch = switch.clone();
        let computed_val1   = val1.clone();
        let computed_val2   = val2.clone();
        let computed        = computed(move || {
            // Use val1 when switch is false, and val2 when switch is true
            if computed_switch.get() {
                computed_val2.get() + 1
            } else {
                computed_val1.get() + 1
            }
        });

        let changed         = bind(false);
        let notify_changed  = changed.clone();
        computed.when_changed(notify(move || notify_changed.set(true))).keep_alive();

        // Initial value of computed (first get 'arms' when_changed too)
        assert!(computed.get() == 2);
        assert!(changed.get() == false);

        // Setting val2 shouldn't cause computed to become 'changed' initially
        val2.set(3);
        assert!(changed.get() == false);
        assert!(computed.get() == 2);

        // ... but setting val1 should
        val1.set(2);
        assert!(changed.get() == true);
        assert!(computed.get() == 3);

        // Flicking the switch will use the val2 value we set earlier
        changed.set(false);
        switch.set(true);
        assert!(changed.get() == true);
        assert!(computed.get() == 4);

        // Updating val2 should now mark us as changed
        changed.set(false);
        val2.set(4);
        assert!(changed.get() == true);
        assert!(computed.get() == 5);
        
        // Updating val1 should not mark us as changed
        changed.set(false);
        val1.set(5);
        assert!(changed.get() == false);
        assert!(computed.get() == 5);
    }

    #[test]
    fn change_during_computation_recomputes() {
        // Create a computed binding that delays for a bit while reading
        let some_binding = bind(1);
        let some_computed = {
            let some_binding = some_binding.clone();
            computed(move || {
                let result = some_binding.get() + 1;
                thread::sleep(Duration::from_millis(250));
                result
            })
        };

        // Start a thread that reads a value
        {
            let some_computed = some_computed.clone();
            thread::spawn(move || {
                assert!(some_computed.get() == 2);
            });
        }

        // Let the thread start running (give it enough time to start computing and reach the sleep statement)
        // TODO: thread::sleep might fail on systems that are slow enough or due to glitches (will fail spuriously if we update the binding before the calculation starts)
        thread::sleep(Duration::from_millis(10));

        // Update the value in the binding while the computed is running
        some_binding.set(2);

        // Computed value should update
        assert!(some_computed.get() == 3);
    }

    #[test]
    fn computed_propagates_changes() {
        let bound               = bind(1);

        let computed_from       = bound.clone();
        let propagates_from     = computed(move || computed_from.get() + 1);
        let computed_propagated = propagates_from.clone();
        let computed            = computed(move || computed_propagated.get() + 1);

        let changed             = bind(false);
        let notify_changed      = changed.clone();
        computed.when_changed(notify(move || notify_changed.set(true))).keep_alive();

        assert!(propagates_from.get() == 2);
        assert!(computed.get() == 3);
        assert!(changed.get() == false);

        bound.set(2);
        assert!(propagates_from.get() == 3);
        assert!(computed.get() == 4);
        assert!(changed.get() == true);

        changed.set(false);
        bound.set(3);
        assert!(changed.get() == true);
        assert!(propagates_from.get() == 4);
        assert!(computed.get() == 5);
    }

    #[test]
    fn computed_stops_notifying_when_released() {
        let bound           = bind(1);

        let computed_from   = bound.clone();
        let computed        = computed(move || computed_from.get() + 1);

        let changed         = bind(false);
        let notify_changed  = changed.clone();
        let mut lifetime    = computed.when_changed(notify(move || notify_changed.set(true)));

        assert!(computed.get() == 2);
        assert!(changed.get() == false);

        bound.set(2);
        assert!(changed.get() == true);
        assert!(computed.get() == 3);

        changed.set(false);
        lifetime.done();

        bound.set(3);
        assert!(changed.get() == false);
        assert!(computed.get() == 4);

        bound.set(4);
        assert!(changed.get() == false);
        assert!(computed.get() == 5);
    }

    #[test]
    fn computed_doesnt_notify_more_than_once() {
        let bound           = bind(1);

        let computed_from   = bound.clone();
        let computed        = computed(move || computed_from.get() + 1);

        let changed         = bind(false);
        let notify_changed  = changed.clone();
        computed.when_changed(notify(move || notify_changed.set(true))).keep_alive();

        assert!(computed.get() == 2);
        assert!(changed.get() == false);

        // Setting the value marks the computed as changed
        bound.set(2);
        assert!(changed.get() == true);
        changed.set(false);

        // ... but when it's already changed we don't notify again
        bound.set(3);
        assert!(changed.get() == false);

        assert!(computed.get() == 4);

        // Once we've retrieved the value, we'll get notified of changes again
        bound.set(4);
        assert!(changed.get() == true);
    }

    #[test]
    fn computed_stops_notifying_once_out_of_scope() {
        let bound           = bind(1);
        let changed         = bind(false);

        {
            let computed_from   = bound.clone();
            let computed        = computed(move || computed_from.get() + 1);

            let notify_changed  = changed.clone();
            computed.when_changed(notify(move || notify_changed.set(true))).keep_alive();

            assert!(computed.get() == 2);
            assert!(changed.get() == false);

            bound.set(2);
            assert!(changed.get() == true);
            assert!(computed.get() == 3);
        };

        // The computed value should have been disposed of so we should get no more notifications once we reach here
        changed.set(false);
        bound.set(3);
        assert!(changed.get() == false);
    }
}