Skip to main content

sui_reactive/
batch.rs

1use std::{cell::RefCell, collections::HashSet, sync::Arc};
2
3use crate::{SignalCore, SourceId};
4
5#[derive(Default)]
6struct BatchState {
7    depth: usize,
8    queued: HashSet<SourceId>,
9    pending: Vec<Arc<SignalCore>>,
10}
11
12thread_local! {
13    static BATCH: RefCell<BatchState> = RefCell::new(BatchState::default());
14}
15
16/// Run `writes` and notify each changed [`Signal`](crate::Signal) once when it
17/// returns, instead of after every write.
18///
19/// Values and versions update immediately, so reads inside the batch see the
20/// new state. Notifications are deferred only for writes made on the calling
21/// thread; other threads are unaffected. Nested batches flush when the
22/// outermost one ends. Each deferred notification carries the signal's
23/// latest version, and is delivered even if `writes` panics, because the
24/// values have already changed.
25///
26/// ```ignore
27/// std::thread::spawn(move || {
28///     let rows = load_rows();
29///     sui_reactive::batch(|| {
30///         rows_signal.set(rows);
31///         status.set(Status::Loaded);
32///         selection.set(None);
33///     }); // observers of each signal run once, here, on this thread
34/// });
35/// ```
36pub fn batch<R>(writes: impl FnOnce() -> R) -> R {
37    BATCH.with(|batch| batch.borrow_mut().depth += 1);
38    let _flush = FlushOnDrop;
39    writes()
40}
41
42struct FlushOnDrop;
43
44impl Drop for FlushOnDrop {
45    fn drop(&mut self) {
46        let pending = BATCH.with(|batch| {
47            let mut batch = batch.borrow_mut();
48            batch.depth -= 1;
49            if batch.depth > 0 {
50                return Vec::new();
51            }
52            batch.queued.clear();
53            std::mem::take(&mut batch.pending)
54        });
55        // The batch is closed, so writes from observers notify immediately.
56        for core in pending {
57            core.deliver();
58        }
59    }
60}
61
62/// Queue `core` if this thread is inside a batch. Returns `false` when the
63/// caller should deliver immediately.
64pub(crate) fn defer(core: &Arc<SignalCore>) -> bool {
65    BATCH
66        .try_with(|batch| {
67            let mut batch = batch.borrow_mut();
68            if batch.depth == 0 {
69                return false;
70            }
71            if batch.queued.insert(core.source_id()) {
72                batch.pending.push(Arc::clone(core));
73            }
74            true
75        })
76        .unwrap_or(false)
77}
78
79#[cfg(test)]
80mod tests {
81    use std::sync::{
82        Arc, Mutex,
83        atomic::{AtomicUsize, Ordering},
84    };
85
86    use crate::{Observable, Observer, Signal, batch};
87
88    #[test]
89    fn batch_notifies_each_signal_once_with_latest_version() {
90        let first = Signal::new(0_u32);
91        let second = Signal::new(0_u32);
92        let log = Arc::new(Mutex::new(Vec::new()));
93        let first_log = Arc::clone(&log);
94        let second_log = Arc::clone(&log);
95        let _first = first.subscribe(Observer::new(move |change| {
96            first_log.lock().unwrap().push(("first", change.version));
97        }));
98        let _second = second.subscribe(Observer::new(move |change| {
99            second_log.lock().unwrap().push(("second", change.version));
100        }));
101
102        batch(|| {
103            first.set(1);
104            second.set(1);
105            first.set(2);
106            batch(|| first.set(3));
107            assert_eq!(first.get(), 3, "reads see writes inside the batch");
108            assert!(log.lock().unwrap().is_empty(), "nested batch did not flush");
109        });
110
111        assert_eq!(*log.lock().unwrap(), vec![("first", 3), ("second", 1)]);
112    }
113
114    #[test]
115    fn selector_over_batched_signal_recomputes_once() {
116        let state = Signal::new((0_u32, 0_u32));
117        let sum = state.select(|(a, b)| a + b);
118        let notifications = Arc::new(AtomicUsize::new(0));
119        let count = Arc::clone(&notifications);
120        let _subscription = sum.subscribe(Observer::new(move |_| {
121            count.fetch_add(1, Ordering::Relaxed);
122        }));
123
124        batch(|| {
125            state.update(|state| state.0 = 1);
126            state.update(|state| state.1 = 2);
127        });
128        assert_eq!(notifications.load(Ordering::Relaxed), 1);
129        assert_eq!(sum.get(), 3);
130    }
131
132    #[test]
133    fn batch_only_defers_the_calling_thread() {
134        let signal = Signal::new(0_u32);
135        let notifications = Arc::new(AtomicUsize::new(0));
136        let count = Arc::clone(&notifications);
137        let _subscription = signal.subscribe(Observer::new(move |_| {
138            count.fetch_add(1, Ordering::Relaxed);
139        }));
140        batch(|| {
141            let writer = signal.clone();
142            std::thread::spawn(move || writer.set(1)).join().unwrap();
143            assert_eq!(notifications.load(Ordering::Relaxed), 1);
144        });
145    }
146
147    #[test]
148    fn batch_flushes_after_a_panic() {
149        let signal = Signal::new(0_u32);
150        let notifications = Arc::new(AtomicUsize::new(0));
151        let count = Arc::clone(&notifications);
152        let _subscription = signal.subscribe(Observer::new(move |_| {
153            count.fetch_add(1, Ordering::Relaxed);
154        }));
155        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
156            batch(|| {
157                signal.set(1);
158                panic!("worker failed");
159            })
160        }));
161        assert!(result.is_err());
162        assert_eq!(notifications.load(Ordering::Relaxed), 1);
163        // The batch closed during unwinding; later writes notify immediately.
164        signal.set(2);
165        assert_eq!(notifications.load(Ordering::Relaxed), 2);
166    }
167}