rx_rust/operators/others/
map_infallible_to_value.rs

1use crate::utils::types::NecessarySendSync;
2use crate::{
3    disposable::subscription::Subscription,
4    observable::Observable,
5    observer::{Observer, Termination},
6    utils::types::MarkerType,
7};
8use educe::Educe;
9use std::{convert::Infallible, marker::PhantomData};
10
11/// Maps an Observable with an `Infallible` item type to an Observable with a concrete item type.
12///
13/// # Examples
14/// ```rust
15/// use rx_rust::{
16///     observable::observable_ext::ObservableExt,
17///     observer::Termination,
18///     operators::{
19///         creating::empty::Empty,
20///         others::map_infallible_to_value::MapInfallibleToValue,
21///     },
22/// };
23///
24/// let mut values = Vec::<i32>::new();
25/// let mut terminations = Vec::new();
26///
27/// MapInfallibleToValue::<i32, _>::new(Empty).subscribe_with_callback(
28///     |value| values.push(value),
29///     |termination| terminations.push(termination),
30/// );
31///
32/// assert!(values.is_empty());
33/// assert_eq!(terminations, vec![Termination::Completed]);
34/// ```
35#[derive(Educe)]
36#[educe(Debug, Clone)]
37pub struct MapInfallibleToValue<T, OE> {
38    source: OE,
39    _marker: MarkerType<T>,
40}
41
42impl<T, OE> MapInfallibleToValue<T, OE> {
43    pub fn new(source: OE) -> Self {
44        Self {
45            source,
46            _marker: PhantomData,
47        }
48    }
49}
50
51impl<'or, 'sub, T, E, OE> Observable<'or, 'sub, T, E> for MapInfallibleToValue<T, OE>
52where
53    T: 'or,
54    OE: Observable<'or, 'sub, Infallible, E>,
55{
56    fn subscribe(
57        self,
58        observer: impl Observer<T, E> + NecessarySendSync + 'or,
59    ) -> Subscription<'sub> {
60        let observer = MapInfallibleToValueObserver {
61            observer,
62            _marker: PhantomData,
63        };
64        self.source.subscribe(observer)
65    }
66}
67
68struct MapInfallibleToValueObserver<T, OR> {
69    observer: OR,
70    _marker: MarkerType<T>,
71}
72
73impl<T, E, OR> Observer<Infallible, E> for MapInfallibleToValueObserver<T, OR>
74where
75    OR: Observer<T, E>,
76{
77    fn on_next(&mut self, _: Infallible) {
78        unreachable!()
79    }
80
81    fn on_termination(self, termination: Termination<E>) {
82        self.observer.on_termination(termination);
83    }
84}