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