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