rx_rust/operators/creating/
from_iter.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/// Converts an `IntoIterator` into an Observable.
11/// See <https://reactivex.io/documentation/operators/from.html>
12///
13/// # Examples
14/// ```rust
15/// use rx_rust::{
16///     observable::observable_ext::ObservableExt,
17///     observer::Termination,
18///     operators::creating::from_iter::FromIter,
19/// };
20///
21/// let mut values = Vec::new();
22/// let mut terminations = Vec::new();
23///
24/// FromIter::new(vec![1, 2, 3]).subscribe_with_callback(
25///     |value| values.push(value),
26///     |termination| terminations.push(termination),
27/// );
28///
29/// assert_eq!(values, vec![1, 2, 3]);
30/// assert_eq!(terminations, vec![Termination::Completed]);
31/// ```
32#[derive(Educe)]
33#[educe(Debug, Clone)]
34pub struct FromIter<I>(I);
35
36impl<I> FromIter<I> {
37    pub fn new(into_iterator: I) -> Self
38    where
39        I: IntoIterator,
40    {
41        Self(into_iterator)
42    }
43}
44
45impl<'or, 'sub, T, I> Observable<'or, 'sub, T, Infallible> for FromIter<I>
46where
47    I: IntoIterator<Item = T>,
48{
49    fn subscribe(
50        self,
51        mut observer: impl Observer<T, Infallible> + NecessarySendSync + 'or,
52    ) -> Subscription<'sub> {
53        for value in self.0.into_iter() {
54            observer.on_next(value);
55        }
56        observer.on_termination(Termination::Completed);
57        Subscription::default()
58    }
59}