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