Skip to main content

rx_rust/operators/creating/
start.rs

1use crate::operators::creating::defer::Defer;
2use crate::operators::creating::just::Just;
3use crate::utils::types::MaybeSend;
4use crate::{
5    observable::{Observable, Subscription},
6    observer::Observer,
7};
8use educe::Educe;
9use std::convert::Infallible;
10
11/// Creates an Observable that emits the return value of a function.
12/// See <https://reactivex.io/documentation/operators/start.html>
13///
14/// # Examples
15/// ```rust
16/// use rx_rust::{
17///     observable::ObservableExt,
18///     observer::Termination,
19///     operators::creating::start::Start,
20/// };
21///
22/// let mut values = Vec::new();
23/// let mut terminations = Vec::new();
24///
25/// Start::new(|| 21 + 21).subscribe_with_callback(
26///     |value| values.push(value),
27///     |termination| terminations.push(termination),
28/// );
29///
30/// assert_eq!(values, vec![42]);
31/// assert_eq!(terminations, vec![Termination::Completed]);
32/// ```
33#[derive(Educe)]
34#[educe(Debug, Clone)]
35pub struct Start<F>(F);
36
37impl<F> Start<F> {
38    pub fn new<T>(builder: F) -> Self
39    where
40        F: FnOnce() -> T,
41    {
42        Self(builder)
43    }
44}
45
46impl<'or, T, F> Observable<'or, T, Infallible> for Start<F>
47where
48    F: FnOnce() -> T,
49{
50    type D = ();
51
52    fn subscribe(
53        self,
54        observer: impl Observer<T, Infallible> + MaybeSend + 'or,
55    ) -> Subscription<Self::D> {
56        Defer::new(|| Just::new(self.0())).subscribe(observer)
57    }
58}