Skip to main content

ftui_runtime/reactive/
observable.rs

1#![forbid(unsafe_code)]
2
3//! Observable value wrapper with change notification and version tracking.
4//!
5//! # Design
6//!
7//! [`Observable<T>`] wraps a value of type `T` in shared, reference-counted
8//! storage (`Rc<RefCell<..>>`). When the value changes (determined by
9//! `PartialEq`), all live subscribers are notified in registration order.
10//!
11//! # Performance
12//!
13//! | Operation    | Complexity               |
14//! |-------------|--------------------------|
15//! | `get()`     | O(1)                     |
16//! | `set()`     | O(S) where S = subscribers |
17//! | `subscribe()` | O(1) amortized          |
18//! | Memory      | ~48 bytes + sizeof(T)    |
19//!
20//! # Failure Modes
21//!
22//! - **Re-entrant set**: Calling `set()` from within a subscriber callback
23//!   will panic (RefCell borrow rules). This is intentional: re-entrant
24//!   mutations indicate a design bug in the subscriber graph.
25//! - **Subscriber leak**: If `Subscription` guards are stored indefinitely
26//!   without being dropped, callbacks accumulate. Dead weak references are
27//!   cleaned lazily during `notify()`.
28
29use std::cell::RefCell;
30use std::rc::{Rc, Weak};
31use tracing::{info, info_span};
32use web_time::Instant;
33
34/// A subscriber callback stored as a strong `Rc` internally, handed out
35/// as `Weak` to the observable.
36type CallbackRc<T> = Rc<dyn Fn(&T)>;
37type CallbackWeak<T> = Weak<dyn Fn(&T)>;
38
39/// Shared interior for [`Observable<T>`].
40struct ObservableInner<T> {
41    value: T,
42    version: u64,
43    /// Subscribers stored as weak references. Dead entries are pruned on notify.
44    subscribers: Vec<CallbackWeak<T>>,
45}
46
47/// A shared, version-tracked value with change notification.
48///
49/// Cloning an `Observable` creates a new handle to the **same** inner state —
50/// both handles see the same value and share subscribers.
51///
52/// # Invariants
53///
54/// 1. `version` increments by exactly 1 on each value-changing mutation.
55/// 2. `set(v)` where `v == current` is a no-op.
56/// 3. Subscribers are notified in registration order.
57/// 4. Dead subscribers (dropped [`Subscription`] guards) are pruned lazily.
58pub struct Observable<T> {
59    inner: Rc<RefCell<ObservableInner<T>>>,
60}
61
62// Manual Clone: shares the same Rc.
63impl<T> Clone for Observable<T> {
64    fn clone(&self) -> Self {
65        Self {
66            inner: Rc::clone(&self.inner),
67        }
68    }
69}
70
71impl<T: std::fmt::Debug> std::fmt::Debug for Observable<T> {
72    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
73        let inner = self.inner.borrow();
74        f.debug_struct("Observable")
75            .field("value", &inner.value)
76            .field("version", &inner.version)
77            .field("subscriber_count", &inner.subscribers.len())
78            .finish()
79    }
80}
81
82impl<T: Clone + PartialEq + 'static> Observable<T> {
83    /// Create a new observable with the given initial value.
84    ///
85    /// The initial version is 0 and no subscribers are registered.
86    #[must_use]
87    pub fn new(value: T) -> Self {
88        Self {
89            inner: Rc::new(RefCell::new(ObservableInner {
90                value,
91                version: 0,
92                subscribers: Vec::new(),
93            })),
94        }
95    }
96
97    /// Get a clone of the current value.
98    #[must_use]
99    pub fn get(&self) -> T {
100        self.inner.borrow().value.clone()
101    }
102
103    /// Access the current value by reference without cloning.
104    ///
105    /// The closure `f` receives an immutable reference to the value.
106    pub fn with<R>(&self, f: impl FnOnce(&T) -> R) -> R {
107        f(&self.inner.borrow().value)
108    }
109
110    /// Set a new value. If the new value differs from the current value
111    /// (by `PartialEq`), the version is incremented and all live subscribers
112    /// are notified.
113    ///
114    /// This method is safe to call re-entrantly from within subscriber callbacks.
115    pub fn set(&self, value: T) {
116        let changed = {
117            let mut inner = self.inner.borrow_mut();
118            if inner.value == value {
119                return;
120            }
121            inner.value = value;
122            inner.version += 1;
123            true
124        };
125        if changed {
126            self.notify();
127        }
128    }
129
130    /// Modify the value in place via a closure. If the value changes
131    /// (compared by `PartialEq` against a snapshot), the version is
132    /// incremented and subscribers are notified.
133    ///
134    /// This method is safe to call re-entrantly from within subscriber callbacks.
135    pub fn update(&self, f: impl FnOnce(&mut T)) {
136        let changed = {
137            let mut inner = self.inner.borrow_mut();
138            let old = inner.value.clone();
139            f(&mut inner.value);
140            if inner.value != old {
141                inner.version += 1;
142                true
143            } else {
144                false
145            }
146        };
147        if changed {
148            self.notify();
149        }
150    }
151
152    /// Subscribe to value changes. The callback is invoked with a reference
153    /// to the new value each time it changes.
154    ///
155    /// Returns a [`Subscription`] guard. Dropping the guard unsubscribes
156    /// the callback (it will not be called after drop, though it may still
157    /// be in the subscriber list until the next `notify()` prunes it).
158    pub fn subscribe(&self, callback: impl Fn(&T) + 'static) -> Subscription {
159        let strong: CallbackRc<T> = Rc::new(callback);
160        let weak = Rc::downgrade(&strong);
161        self.inner.borrow_mut().subscribers.push(weak);
162        // Wrap in a holder struct that can be type-erased as `dyn Any`,
163        // since `Rc<dyn Fn(&T)>` itself cannot directly coerce to `Rc<dyn Any>`.
164        Subscription {
165            _guard: Box::new(strong),
166        }
167    }
168
169    /// Current version number. Increments by 1 on each value-changing
170    /// mutation. Useful for dirty-checking in render loops.
171    #[must_use]
172    pub fn version(&self) -> u64 {
173        self.inner.borrow().version
174    }
175
176    /// Number of currently registered subscribers (including dead ones
177    /// not yet pruned).
178    #[must_use]
179    pub fn subscriber_count(&self) -> usize {
180        self.inner.borrow().subscribers.len()
181    }
182
183    /// Notify live subscribers and prune dead ones.
184    ///
185    /// If a batch scope is active (see [`super::batch::BatchScope`]),
186    /// notifications are deferred until the batch exits.
187    fn notify(&self) {
188        // Collect live callbacks first (to avoid holding the borrow during calls).
189        let callbacks: Vec<CallbackRc<T>> = {
190            let mut inner = self.inner.borrow_mut();
191            // Prune dead weak refs and collect live ones.
192            inner.subscribers.retain(|w| w.strong_count() > 0);
193            inner
194                .subscribers
195                .iter()
196                .filter_map(|w| w.upgrade())
197                .collect()
198        };
199
200        if callbacks.is_empty() {
201            return;
202        }
203
204        let widgets_invalidated = callbacks.len() as u64;
205
206        if super::batch::is_batching() {
207            super::batch::record_rows_changed(1);
208            // Defer each callback to the batch queue.
209            for cb in callbacks {
210                let callback_key = Rc::as_ptr(&cb) as *const () as usize;
211                let source = self.clone();
212                super::batch::defer_or_run_keyed(callback_key, move || {
213                    let latest = source.get();
214                    cb(&latest);
215                });
216            }
217            return;
218        }
219
220        // Borrow the value during callbacks to prevent re-entrant mutations.
221        let inner = self.inner.borrow();
222        let propagation_start = Instant::now();
223        let _span = info_span!(
224            "bloodstream.delta",
225            rows_changed = 1_u64,
226            widgets_invalidated,
227            duration_us = tracing::field::Empty
228        )
229        .entered();
230
231        // Fire immediately.
232        for cb in &callbacks {
233            cb(&inner.value);
234        }
235
236        let duration_us = propagation_start.elapsed().as_micros() as u64;
237        tracing::Span::current().record("duration_us", duration_us);
238        info!(
239            bloodstream_propagation_duration_us = duration_us,
240            rows_changed = 1_u64,
241            widgets_invalidated,
242            "bloodstream propagation duration histogram"
243        );
244    }
245}
246
247/// RAII guard for a subscriber callback.
248///
249/// Dropping the `Subscription` causes the associated callback to become
250/// unreachable (the strong `Rc` is dropped, so the `Weak` in the
251/// observable's subscriber list will fail to upgrade on the next
252/// notification cycle).
253pub struct Subscription {
254    /// Type-erased strong reference keeping the callback `Rc` alive.
255    /// When this `Box<dyn Any>` is dropped, the inner `Rc<dyn Fn(&T)>`
256    /// is dropped, and the corresponding `Weak` in the subscriber list
257    /// loses its referent.
258    _guard: Box<dyn std::any::Any>,
259}
260
261impl Subscription {
262    /// Combine multiple subscriptions into a single composite subscription.
263    #[must_use]
264    pub fn composite(subscriptions: Vec<Subscription>) -> Self {
265        Self {
266            _guard: Box::new(subscriptions),
267        }
268    }
269}
270
271impl std::fmt::Debug for Subscription {
272    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
273        f.debug_struct("Subscription").finish_non_exhaustive()
274    }
275}
276
277// ---------------------------------------------------------------------------
278// Tests
279// ---------------------------------------------------------------------------
280
281#[cfg(test)]
282mod tests {
283    use super::*;
284    use std::cell::Cell;
285    use std::sync::atomic::{AtomicU64, Ordering};
286    use std::sync::{Arc, Mutex};
287    use tracing::field::{Field, Visit};
288
289    #[derive(Clone, Debug, PartialEq, Eq)]
290    struct TableSnapshot {
291        schema_version: u64,
292        rows: Vec<String>,
293    }
294
295    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
296    enum RenderMode {
297        PartialDelta,
298        FullRerender,
299    }
300
301    fn classify_render_mode(previous: &TableSnapshot, next: &TableSnapshot) -> RenderMode {
302        if previous.schema_version != next.schema_version {
303            RenderMode::FullRerender
304        } else {
305            RenderMode::PartialDelta
306        }
307    }
308
309    #[derive(Default)]
310    struct DeltaSpanVisitor {
311        rows_changed: Option<u64>,
312        widgets_invalidated: Option<u64>,
313    }
314
315    impl Visit for DeltaSpanVisitor {
316        fn record_u64(&mut self, field: &Field, value: u64) {
317            match field.name() {
318                "rows_changed" => self.rows_changed = Some(value),
319                "widgets_invalidated" => self.widgets_invalidated = Some(value),
320                _ => {}
321            }
322        }
323
324        fn record_i64(&mut self, field: &Field, value: i64) {
325            if value < 0 {
326                return;
327            }
328            self.record_u64(field, value as u64);
329        }
330
331        fn record_debug(&mut self, _field: &Field, _value: &dyn std::fmt::Debug) {}
332    }
333
334    struct DeltaSpanSubscriber {
335        next_id: AtomicU64,
336        spans: Arc<Mutex<Vec<(u64, u64)>>>,
337    }
338
339    impl tracing::Subscriber for DeltaSpanSubscriber {
340        fn enabled(&self, _metadata: &tracing::Metadata<'_>) -> bool {
341            true
342        }
343
344        fn new_span(&self, attrs: &tracing::span::Attributes<'_>) -> tracing::span::Id {
345            if attrs.metadata().name() == "bloodstream.delta" {
346                let mut visitor = DeltaSpanVisitor::default();
347                attrs.record(&mut visitor);
348                self.spans.lock().expect("span capture lock").push((
349                    visitor.rows_changed.unwrap_or(0),
350                    visitor.widgets_invalidated.unwrap_or(0),
351                ));
352            }
353            tracing::span::Id::from_u64(self.next_id.fetch_add(1, Ordering::Relaxed))
354        }
355
356        fn record(&self, _span: &tracing::span::Id, _values: &tracing::span::Record<'_>) {}
357
358        fn record_follows_from(&self, _span: &tracing::span::Id, _follows: &tracing::span::Id) {}
359
360        fn event(&self, _event: &tracing::Event<'_>) {}
361
362        fn enter(&self, _span: &tracing::span::Id) {}
363
364        fn exit(&self, _span: &tracing::span::Id) {}
365    }
366
367    fn capture_delta_spans(run: impl FnOnce()) -> Vec<(u64, u64)> {
368        let spans = Arc::new(Mutex::new(Vec::new()));
369        let subscriber = DeltaSpanSubscriber {
370            next_id: AtomicU64::new(1),
371            spans: Arc::clone(&spans),
372        };
373        let _guard = tracing::subscriber::set_default(subscriber);
374        run();
375        spans.lock().expect("span capture lock").clone()
376    }
377
378    #[test]
379    fn get_set_basic() {
380        let obs = Observable::new(42);
381        assert_eq!(obs.get(), 42);
382        assert_eq!(obs.version(), 0);
383
384        obs.set(99);
385        assert_eq!(obs.get(), 99);
386        assert_eq!(obs.version(), 1);
387    }
388
389    #[test]
390    fn no_change_no_version_bump() {
391        let obs = Observable::new(42);
392        obs.set(42); // Same value.
393        assert_eq!(obs.version(), 0);
394    }
395
396    #[test]
397    fn with_access() {
398        let obs = Observable::new(vec![1, 2, 3]);
399        let sum = obs.with(|v| v.iter().sum::<i32>());
400        assert_eq!(sum, 6);
401    }
402
403    #[test]
404    fn update_mutates_in_place() {
405        let obs = Observable::new(vec![1, 2, 3]);
406        obs.update(|v| v.push(4));
407        assert_eq!(obs.get(), vec![1, 2, 3, 4]);
408        assert_eq!(obs.version(), 1);
409    }
410
411    #[test]
412    fn update_no_change_no_bump() {
413        let obs = Observable::new(10);
414        obs.update(|v| {
415            *v = 10; // Same value.
416        });
417        assert_eq!(obs.version(), 0);
418    }
419
420    #[test]
421    fn change_notification() {
422        let obs = Observable::new(0);
423        let count = Rc::new(Cell::new(0u32));
424        let count_clone = Rc::clone(&count);
425
426        let _sub = obs.subscribe(move |_val| {
427            count_clone.set(count_clone.get() + 1);
428        });
429
430        obs.set(1);
431        assert_eq!(count.get(), 1);
432
433        obs.set(2);
434        assert_eq!(count.get(), 2);
435
436        // Same value — no notification.
437        obs.set(2);
438        assert_eq!(count.get(), 2);
439    }
440
441    #[test]
442    fn subscriber_receives_new_value() {
443        let obs = Observable::new(0);
444        let last_seen = Rc::new(Cell::new(0));
445        let last_clone = Rc::clone(&last_seen);
446
447        let _sub = obs.subscribe(move |val| {
448            last_clone.set(*val);
449        });
450
451        obs.set(42);
452        assert_eq!(last_seen.get(), 42);
453
454        obs.set(99);
455        assert_eq!(last_seen.get(), 99);
456    }
457
458    #[test]
459    fn subscription_drop_unsubscribes() {
460        let obs = Observable::new(0);
461        let count = Rc::new(Cell::new(0u32));
462        let count_clone = Rc::clone(&count);
463
464        let sub = obs.subscribe(move |_val| {
465            count_clone.set(count_clone.get() + 1);
466        });
467
468        obs.set(1);
469        assert_eq!(count.get(), 1);
470
471        drop(sub);
472
473        obs.set(2);
474        // Callback should NOT have been called.
475        assert_eq!(count.get(), 1);
476    }
477
478    #[test]
479    fn multiple_subscribers() {
480        let obs = Observable::new(0);
481        let a = Rc::new(Cell::new(0u32));
482        let b = Rc::new(Cell::new(0u32));
483        let a_clone = Rc::clone(&a);
484        let b_clone = Rc::clone(&b);
485
486        let _sub_a = obs.subscribe(move |_| a_clone.set(a_clone.get() + 1));
487        let _sub_b = obs.subscribe(move |_| b_clone.set(b_clone.get() + 1));
488
489        obs.set(1);
490        assert_eq!(a.get(), 1);
491        assert_eq!(b.get(), 1);
492
493        obs.set(2);
494        assert_eq!(a.get(), 2);
495        assert_eq!(b.get(), 2);
496    }
497
498    #[test]
499    fn version_increment() {
500        let obs = Observable::new("hello".to_string());
501        assert_eq!(obs.version(), 0);
502
503        obs.set("world".to_string());
504        assert_eq!(obs.version(), 1);
505
506        obs.set("!".to_string());
507        assert_eq!(obs.version(), 2);
508
509        // Same value, no increment.
510        obs.set("!".to_string());
511        assert_eq!(obs.version(), 2);
512    }
513
514    #[test]
515    fn clone_shares_state() {
516        let obs1 = Observable::new(0);
517        let obs2 = obs1.clone();
518
519        obs1.set(42);
520        assert_eq!(obs2.get(), 42);
521        assert_eq!(obs2.version(), 1);
522
523        obs2.set(99);
524        assert_eq!(obs1.get(), 99);
525        assert_eq!(obs1.version(), 2);
526    }
527
528    #[test]
529    fn clone_shares_subscribers() {
530        let obs1 = Observable::new(0);
531        let count = Rc::new(Cell::new(0u32));
532        let count_clone = Rc::clone(&count);
533
534        let _sub = obs1.subscribe(move |_| count_clone.set(count_clone.get() + 1));
535
536        let obs2 = obs1.clone();
537        obs2.set(1);
538        assert_eq!(count.get(), 1); // Subscriber sees change via clone.
539    }
540
541    #[test]
542    fn subscriber_count() {
543        let obs = Observable::new(0);
544        assert_eq!(obs.subscriber_count(), 0);
545
546        let _s1 = obs.subscribe(|_| {});
547        assert_eq!(obs.subscriber_count(), 1);
548
549        let s2 = obs.subscribe(|_| {});
550        assert_eq!(obs.subscriber_count(), 2);
551
552        drop(s2);
553        // Dead subscriber not yet pruned.
554        assert_eq!(obs.subscriber_count(), 2);
555
556        // Trigger notify to prune dead.
557        obs.set(1);
558        assert_eq!(obs.subscriber_count(), 1);
559    }
560
561    #[test]
562    fn debug_format() {
563        let obs = Observable::new(42);
564        let dbg = format!("{:?}", obs);
565        assert!(dbg.contains("Observable"));
566        assert!(dbg.contains("42"));
567        assert!(dbg.contains("version"));
568    }
569
570    #[test]
571    fn notification_order_is_registration_order() {
572        let obs = Observable::new(0);
573        let log = Rc::new(RefCell::new(Vec::new()));
574
575        let log1 = Rc::clone(&log);
576        let _s1 = obs.subscribe(move |_| log1.borrow_mut().push('A'));
577
578        let log2 = Rc::clone(&log);
579        let _s2 = obs.subscribe(move |_| log2.borrow_mut().push('B'));
580
581        let log3 = Rc::clone(&log);
582        let _s3 = obs.subscribe(move |_| log3.borrow_mut().push('C'));
583
584        obs.set(1);
585        assert_eq!(*log.borrow(), vec!['A', 'B', 'C']);
586    }
587
588    #[test]
589    fn update_with_subscriber() {
590        let obs = Observable::new(vec![1, 2, 3]);
591        let last_len = Rc::new(Cell::new(0usize));
592        let last_clone = Rc::clone(&last_len);
593
594        let _sub = obs.subscribe(move |v: &Vec<i32>| {
595            last_clone.set(v.len());
596        });
597
598        obs.update(|v| v.push(4));
599        assert_eq!(last_len.get(), 4);
600    }
601
602    #[test]
603    fn many_set_calls_version_monotonic() {
604        let obs = Observable::new(0);
605        for i in 1..=100 {
606            obs.set(i);
607        }
608        assert_eq!(obs.version(), 100);
609        assert_eq!(obs.get(), 100);
610    }
611
612    #[test]
613    fn partial_subscriber_drop() {
614        let obs = Observable::new(0);
615        let a = Rc::new(Cell::new(0u32));
616        let b = Rc::new(Cell::new(0u32));
617        let a_clone = Rc::clone(&a);
618        let b_clone = Rc::clone(&b);
619
620        let sub_a = obs.subscribe(move |_| a_clone.set(a_clone.get() + 1));
621        let _sub_b = obs.subscribe(move |_| b_clone.set(b_clone.get() + 1));
622
623        obs.set(1);
624        assert_eq!(a.get(), 1);
625        assert_eq!(b.get(), 1);
626
627        drop(sub_a);
628
629        obs.set(2);
630        assert_eq!(a.get(), 1); // A was unsubscribed.
631        assert_eq!(b.get(), 2); // B still active.
632    }
633
634    #[test]
635    fn single_row_change_propagates_only_to_bound_widgets() {
636        let row_a = Observable::new(vec!["a".to_string()]);
637        let row_b = Observable::new(vec!["b".to_string()]);
638        let a_hits = Rc::new(Cell::new(0u32));
639        let b_hits = Rc::new(Cell::new(0u32));
640        let a_hits_clone = Rc::clone(&a_hits);
641        let b_hits_clone = Rc::clone(&b_hits);
642
643        let _sub_a = row_a.subscribe(move |_| a_hits_clone.set(a_hits_clone.get() + 1));
644        let _sub_b = row_b.subscribe(move |_| b_hits_clone.set(b_hits_clone.get() + 1));
645
646        row_a.set(vec!["a2".to_string()]);
647        assert_eq!(a_hits.get(), 1, "bound row-A widget should be invalidated");
648        assert_eq!(
649            b_hits.get(),
650            0,
651            "unbound row-B widget should remain untouched"
652        );
653    }
654
655    #[test]
656    fn batch_delta_propagates_atomically_without_stale_intermediate_values() {
657        let rows = Observable::new(vec!["r0".to_string()]);
658        let seen = Rc::new(RefCell::new(Vec::<Vec<String>>::new()));
659        let seen_clone = Rc::clone(&seen);
660        let _sub = rows.subscribe(move |current| seen_clone.borrow_mut().push(current.clone()));
661
662        {
663            let _batch = crate::reactive::batch::BatchScope::new();
664            rows.set(vec!["r1".to_string()]);
665            rows.set(vec!["r1".to_string(), "r2".to_string()]);
666            rows.update(|current| current.push("r3".to_string()));
667            assert!(
668                seen.borrow().is_empty(),
669                "callbacks must be deferred until batch exit"
670            );
671        }
672
673        let snapshots = seen.borrow();
674        assert_eq!(
675            snapshots.len(),
676            1,
677            "batched updates should coalesce to one invalidation"
678        );
679        assert_eq!(
680            snapshots[0],
681            vec!["r1".to_string(), "r2".to_string(), "r3".to_string()],
682            "subscriber must observe only final state"
683        );
684    }
685
686    #[test]
687    fn unbound_table_updates_produce_no_bloodstream_delta() {
688        let table_rows = Observable::new(vec!["old".to_string()]);
689        let spans = capture_delta_spans(|| {
690            table_rows.set(vec!["new".to_string()]);
691        });
692        assert!(
693            spans.is_empty(),
694            "unbound table updates should not emit bloodstream deltas"
695        );
696    }
697
698    #[test]
699    fn bloodstream_delta_span_reports_rows_changed_and_widgets_invalidated() {
700        let table_rows = Observable::new(vec!["old".to_string()]);
701        let _sub_a = table_rows.subscribe(|_| {});
702        let _sub_b = table_rows.subscribe(|_| {});
703
704        let spans = capture_delta_spans(|| {
705            table_rows.set(vec!["new".to_string()]);
706        });
707        assert_eq!(
708            spans,
709            vec![(1, 2)],
710            "single-row change should report one row and two invalidated widgets"
711        );
712    }
713
714    #[test]
715    fn schema_change_requires_full_rerender_not_partial_delta() {
716        let table = Observable::new(TableSnapshot {
717            schema_version: 1,
718            rows: vec!["alpha".to_string()],
719        });
720        let previous = Rc::new(RefCell::new(Some(table.get())));
721        let decisions = Rc::new(RefCell::new(Vec::<RenderMode>::new()));
722        let previous_clone = Rc::clone(&previous);
723        let decisions_clone = Rc::clone(&decisions);
724
725        let _sub = table.subscribe(move |next| {
726            let mut prev = previous_clone.borrow_mut();
727            let current_mode =
728                classify_render_mode(prev.as_ref().expect("previous snapshot available"), next);
729            decisions_clone.borrow_mut().push(current_mode);
730            *prev = Some(next.clone());
731        });
732
733        table.set(TableSnapshot {
734            schema_version: 1,
735            rows: vec!["alpha".to_string(), "beta".to_string()],
736        });
737        table.set(TableSnapshot {
738            schema_version: 2,
739            rows: vec!["alpha".to_string(), "beta".to_string()],
740        });
741
742        assert_eq!(
743            *decisions.borrow(),
744            vec![RenderMode::PartialDelta, RenderMode::FullRerender],
745            "schema-version changes must force full rerender semantics"
746        );
747    }
748
749    #[test]
750    fn string_observable() {
751        let obs = Observable::new(String::new());
752        let changes = Rc::new(Cell::new(0u32));
753        let changes_clone = Rc::clone(&changes);
754
755        let _sub = obs.subscribe(move |_| changes_clone.set(changes_clone.get() + 1));
756
757        obs.set("hello".to_string());
758        obs.set("hello".to_string()); // Same, no notify.
759        obs.set("world".to_string());
760
761        assert_eq!(changes.get(), 2);
762        assert_eq!(obs.version(), 2);
763    }
764}