rx_rust/operators/creating/
from_result.rs

1use crate::utils::types::NecessarySend;
2use crate::{
3    disposable::subscription::Subscription,
4    observable::Observable,
5    observer::{Observer, Termination},
6};
7use educe::Educe;
8
9/// Converts a `Result` into an Observable.
10/// See <https://reactivex.io/documentation/operators/from.html>
11///
12/// # Examples
13/// ```rust
14/// use rx_rust::{
15///     observable::observable_ext::ObservableExt,
16///     observer::Termination,
17///     operators::creating::from_result::FromResult,
18/// };
19///
20/// let mut values = Vec::new();
21/// let mut terminations = Vec::new();
22///
23/// FromResult::new(Ok::<i32, &str>(10)).subscribe_with_callback(
24///     |value| values.push(value),
25///     |termination| terminations.push(termination),
26/// );
27///
28/// assert_eq!(values, vec![10]);
29/// assert_eq!(terminations, vec![Termination::Completed]);
30/// ```
31#[derive(Educe)]
32#[educe(Debug, Clone)]
33pub struct FromResult<T, E>(Result<T, E>);
34
35impl<T, E> FromResult<T, E> {
36    pub fn new(result: Result<T, E>) -> Self {
37        Self(result)
38    }
39}
40
41impl<'or, 'sub, T, E> Observable<'or, 'sub, T, E> for FromResult<T, E> {
42    fn subscribe(
43        self,
44        mut observer: impl Observer<T, E> + NecessarySend + 'or,
45    ) -> Subscription<'sub> {
46        match self.0 {
47            Ok(value) => {
48                observer.on_next(value);
49                observer.on_termination(Termination::Completed);
50            }
51            Err(error) => observer.on_termination(Termination::Error(error)),
52        }
53        Subscription::default()
54    }
55}