Skip to main content

rx_rust/operators/creating/
just.rs

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