Skip to main content

rx_rust/observable/
either_observable.rs

1use super::{Observable, Subscription};
2use crate::{
3    disposable::either_disposal::EitherDisposal, observer::Observer, utils::types::MaybeSend,
4};
5use educe::Educe;
6
7/// An observable that is one of two concrete observable types.
8///
9/// Unlike [`super::boxed_observable::BoxedObservable`], this type preserves static
10/// dispatch and does not allocate. It is useful when the set of possible observable
11/// types is known at compile time.
12#[derive(Educe)]
13#[educe(Debug, Clone)]
14pub enum EitherObservable<A, B> {
15    Left(A),
16    Right(B),
17}
18
19impl<'or, T, E, A, B> Observable<'or, T, E> for EitherObservable<A, B>
20where
21    A: Observable<'or, T, E>,
22    B: Observable<'or, T, E>,
23{
24    type D = EitherDisposal<Subscription<A::D>, Subscription<B::D>>;
25
26    fn subscribe(self, observer: impl Observer<T, E> + MaybeSend + 'or) -> Subscription<Self::D> {
27        match self {
28            Self::Left(observable) => {
29                Subscription::new(EitherDisposal::Left(observable.subscribe(observer)))
30            }
31            Self::Right(observable) => {
32                Subscription::new(EitherDisposal::Right(observable.subscribe(observer)))
33            }
34        }
35    }
36}