Skip to main content

sui_reactive/
combine.rs

1use std::sync::Arc;
2
3use crate::{Observable, Observer, Selector, SourceId, Subscription};
4
5/// Several observables viewed as one tuple-valued source. Built by
6/// [`combine`]; observing it directly notifies on a change to any input.
7pub struct Zip<S> {
8    id: SourceId,
9    name: Arc<str>,
10    sources: S,
11}
12
13/// Derive a value from up to four observables.
14///
15/// ```ignore
16/// let summary = combine((items.clone(), filter.clone()), |(items, filter)| {
17///     items.iter().filter(|item| filter.matches(item)).count()
18/// });
19/// ```
20///
21/// The result is a [`Selector`]: it notifies only when the derived value
22/// changes, runs `combine` once per input change however many observers it
23/// has, and caches the result while no input changes. Unlike a selector over
24/// one source, each input is cloned to build the tuple, because holding
25/// several inputs' locks at once could deadlock against writers. Combine
26/// narrow selectors or `Arc` values rather than large state.
27pub fn combine<S, I, O>(
28    sources: S,
29    combine: impl Fn(&I) -> O + Send + Sync + 'static,
30) -> Selector<Zip<S>, I, O>
31where
32    Zip<S>: Observable<I>,
33{
34    combine_named("Combined", sources, combine)
35}
36
37/// [`combine`] with a diagnostics name.
38pub fn combine_named<S, I, O>(
39    name: impl Into<Arc<str>>,
40    sources: S,
41    combine: impl Fn(&I) -> O + Send + Sync + 'static,
42) -> Selector<Zip<S>, I, O>
43where
44    Zip<S>: Observable<I>,
45{
46    let name = name.into();
47    let zip = Zip {
48        id: SourceId::new(),
49        name: Arc::clone(&name),
50        sources,
51    };
52    Selector::new(name, zip, combine)
53}
54
55macro_rules! impl_zip {
56    ($(($source:ident, $value:ident, $index:tt)),+) => {
57        impl<$($source, $value),+> Observable<($($value,)+)> for Zip<($($source,)+)>
58        where
59            $($source: Observable<$value>,)+
60        {
61            fn source_id(&self) -> SourceId {
62                self.id
63            }
64
65            fn source_name(&self) -> Arc<str> {
66                Arc::clone(&self.name)
67            }
68
69            fn get(&self) -> ($($value,)+) {
70                ($(self.sources.$index.get(),)+)
71            }
72
73            fn value_version(&self) -> Option<u64> {
74                // Every input change raises the sum, and each input's version
75                // is read before its value, so the sum is a valid version.
76                let mut version = 0_u64;
77                $(version = version.checked_add(self.sources.$index.value_version()?)?;)+
78                Some(version)
79            }
80
81            fn subscribe(&self, observer: Observer) -> Subscription {
82                let inputs = vec![$(self.sources.$index.subscribe(observer.clone())),+];
83                Subscription::with_release(observer, inputs)
84            }
85        }
86    };
87}
88
89impl_zip!((SA, A, 0), (SB, B, 1));
90impl_zip!((SA, A, 0), (SB, B, 1), (SC, C, 2));
91impl_zip!((SA, A, 0), (SB, B, 1), (SC, C, 2), (SD, D, 3));
92
93#[cfg(test)]
94mod tests {
95    use std::sync::{
96        Arc,
97        atomic::{AtomicUsize, Ordering},
98    };
99
100    use crate::{Observable, Observer, Signal, batch, combine, combine_named};
101
102    #[test]
103    fn combine_derives_from_several_sources() {
104        let count = Signal::new(2_u32);
105        let label = Signal::new("apples".to_string());
106        let runs = Arc::new(AtomicUsize::new(0));
107        let counter = Arc::clone(&runs);
108        let summary = combine((count.clone(), label.clone()), move |(count, label)| {
109            counter.fetch_add(1, Ordering::Relaxed);
110            format!("{count} {label}")
111        });
112        let notifications = Arc::new(AtomicUsize::new(0));
113        let notified = Arc::clone(&notifications);
114        let _subscription = summary.subscribe(Observer::new(move |_| {
115            notified.fetch_add(1, Ordering::Relaxed);
116        }));
117
118        assert_eq!(summary.get(), "2 apples");
119        count.set(3);
120        label.set("pears".to_string());
121        assert_eq!(summary.get(), "3 pears");
122        assert_eq!(notifications.load(Ordering::Relaxed), 2);
123
124        let before = runs.load(Ordering::Relaxed);
125        batch(|| {
126            count.set(4);
127            label.set("plums".to_string());
128        });
129        // Each changed input notifies the selector, but both inputs had
130        // changed by the first notification: the second hits the cache and is
131        // deduplicated.
132        assert_eq!(notifications.load(Ordering::Relaxed), 3);
133        assert_eq!(summary.get(), "4 plums");
134        assert_eq!(runs.load(Ordering::Relaxed) - before, 1);
135    }
136
137    #[test]
138    fn combine_accepts_selectors_and_four_inputs() {
139        let a = Signal::new((1_u8, "unused"));
140        let first = a.select(|(value, _)| *value);
141        let b = Signal::new(2_u8);
142        let c = Signal::new(3_u8);
143        let d = Signal::new(4_u8);
144        let sum = combine_named("sum", (first, b, c, d.clone()), |(a, b, c, d)| {
145            a + b + c + d
146        });
147        assert_eq!(sum.get(), 10);
148        d.set(5);
149        assert_eq!(sum.get(), 11);
150        assert_eq!(&*sum.source_name(), "sum");
151    }
152}