rx_rust/operators/creating/
start.rs

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