futures_rx/
stream_ext.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
use std::{collections::VecDeque, future::Future, hash::Hash, vec::IntoIter};

use buffer::Buffer;
use debounce::Debounce;
use dematerialize::Dematerialize;
use distinct::Distinct;
use distinct_until_changed::DistinctUntilChanged;
use futures::{stream::Iter, Stream};
use materialize::Materialize;
use pairwise::Pairwise;
use race::Race;
use share::Shared;
use start_with::StartWith;
use switch_map::SwitchMap;
use window::Window;

use crate::{BehaviorSubject, CombineLatest2, Event, Notification, PublishSubject, ReplaySubject};

use self::{delay::Delay, end_with::EndWith, throttle::Throttle};

pub mod buffer;
pub mod debounce;
pub mod delay;
pub mod dematerialize;
pub mod distinct;
pub mod distinct_until_changed;
pub mod end_with;
pub mod materialize;
pub mod pairwise;
pub mod race;
pub mod share;
pub mod start_with;
pub mod switch_map;
pub mod throttle;
pub mod window;

impl<T: ?Sized> RxExt for T where T: Stream {}
pub trait RxExt: Stream {
    /// Starts polling itself as well as the provided other `Stream`.
    /// The first one to emit an event "wins" and proceeds to emit all its next events.
    /// The "loser" is discarded and will not be polled further.
    ///
    /// Note that this function consumes the stream passed into it and returns a
    /// wrapped version of it.
    ///
    /// # Examples
    ///
    /// ```
    /// # futures::executor::block_on(async {
    /// use futures::stream::{self, StreamExt};
    /// use futures_rx::{Notification, RxExt};
    ///
    /// let stream = stream::iter(0..=3);
    /// let slower_stream = stream::iter(4..=6).delay(|| async { /* return delayed over time */ });
    /// let stream = stream.race(slower_stream);
    ///
    /// assert_eq!(vec![0, 1, 2, 3], stream.collect::<Vec<_>>().await);
    /// # });
    ///
    /// #
    /// ```
    fn race<S: Stream<Item = Self::Item>>(self, other: S) -> Race<Self, S, Self::Item>
    where
        Self: Sized,
    {
        assert_stream::<Self::Item, _>(Race::new(self, other))
    }

    /// Precedes all emitted events with the items of an iter.
    ///
    /// Note that this function consumes the stream passed into it and returns a
    /// wrapped version of it.
    ///
    /// # Examples
    ///
    /// ```
    /// # futures::executor::block_on(async {
    /// use futures::stream::{self, StreamExt};
    /// use futures_rx::{Notification, RxExt};
    ///
    /// let stream = stream::iter(4..=6);
    /// let stream = stream.start_with(0..=3);
    ///
    /// assert_eq!(vec![0, 1, 2, 3, 4, 5, 6], stream.collect::<Vec<_>>().await);
    /// # });
    ///
    /// #
    /// ```
    fn start_with<I: IntoIterator<Item = Self::Item>>(self, iter: I) -> StartWith<Self>
    where
        Self: Sized,
    {
        assert_stream::<Self::Item, _>(StartWith::new(self, iter))
    }

    /// Follows all emitted events with the items of an iter.
    ///
    /// Note that this function consumes the stream passed into it and returns a
    /// wrapped version of it.
    ///
    /// # Examples
    ///
    /// ```
    /// # futures::executor::block_on(async {
    /// use futures::stream::{self, StreamExt};
    /// use futures_rx::{Notification, RxExt};
    ///
    /// let stream = stream::iter(0..=3);
    /// let stream = stream.end_with(4..=6);
    ///
    /// assert_eq!(vec![0, 1, 2, 3, 4, 5, 6], stream.collect::<Vec<_>>().await);
    /// # });
    ///
    /// #
    /// ```
    fn end_with<I: IntoIterator<Item = Self::Item>>(self, iter: I) -> EndWith<Self>
    where
        Self: Sized,
    {
        assert_stream::<Self::Item, _>(EndWith::new(self, iter))
    }

    /// Transforms a `Stream` into a broadcast one, which can be subscribed to more than once, after cloning the shared version.
    ///
    /// Behavior is exactly like a `PublishSubject`, every new subscription will produce a unique `Stream` which only emits `Event` objects.
    /// An `Event` is a helper object which wraps a ref counted value.
    ///
    /// Note that this function consumes the stream passed into it and returns a
    /// wrapped version of it.
    ///
    /// # Examples
    ///
    /// ```
    /// # futures::executor::block_on(async {
    /// use futures::{stream::{StreamExt, self}, future::join};
    /// use futures_rx::{Notification, RxExt};
    ///
    /// let stream = stream::iter(0..=3);
    /// let stream = stream.share();
    /// let sub_stream_a = stream.clone().map(|event| *event); // an event is Event here, wrapping a ref counted value
    /// let sub_stream_b = stream.clone().map(|event| *event); // which we can just deref in this case to i32
    ///
    /// assert_eq!((vec![0, 1, 2, 3], vec![0, 1, 2, 3]), join(sub_stream_a.collect::<Vec<_>>(), sub_stream_b.collect::<Vec<_>>()).await);
    /// # });
    ///
    /// #
    /// ```
    fn share(self) -> Shared<Self, PublishSubject<Self::Item>>
    where
        Self: Sized,
    {
        assert_stream::<Event<Self::Item>, _>(Shared::new(self, PublishSubject::new()))
    }

    /// Transforms a `Stream` into a broadcast one, which can be subscribed to more than once, after cloning the shared version.
    ///
    /// Behavior is exactly like a `BehaviorSubject`, where every new subscription will always receive the last emitted event
    /// from the parent `Stream` first.
    /// Every new subscription will produce a unique `Stream` which only emits `Event` objects.
    /// An `Event` is a helper object which wraps a ref counted value.
    ///
    /// Note that this function consumes the stream passed into it and returns a
    /// wrapped version of it.
    ///
    /// # Examples
    ///
    /// ```
    /// # futures::executor::block_on(async {
    /// use futures::{stream::{StreamExt, self}, future::join};
    /// use futures_rx::{Notification, RxExt};
    ///
    /// let stream = stream::iter(0..=3);
    /// let stream = stream.share_behavior();
    ///
    /// stream.clone().collect::<Vec<_>>().await; // consume all events beforehand
    ///
    /// let sub_stream_a = stream.clone().map(|event| *event); // an event is Event here, wrapping a ref counted value
    /// let sub_stream_b = stream.clone().map(|event| *event); // which we can just deref in this case to i32
    ///
    /// assert_eq!(
    ///     (vec![3], vec![3]),
    ///     join(
    ///         sub_stream_a.collect::<Vec<_>>(),
    ///         sub_stream_b.collect::<Vec<_>>()
    ///     )
    ///     .await
    /// );
    /// # });
    ///
    /// #
    /// ```
    fn share_behavior(self) -> Shared<Self, BehaviorSubject<Self::Item>>
    where
        Self: Sized,
    {
        assert_stream::<Event<Self::Item>, _>(Shared::new(self, BehaviorSubject::new()))
    }

    /// Transforms a `Stream` into a broadcast one, which can be subscribed to more than once, after cloning the shared version.
    ///
    /// Behavior is exactly like a `ReplaySubject`, where every new subscription will always receive all previously emitted events
    /// from the parent `Stream` first.
    /// Every new subscription will produce a unique `Stream` which only emits `Event` objects.
    /// An `Event` is a helper object which wraps a ref counted value.
    ///
    /// Note that this function consumes the stream passed into it and returns a
    /// wrapped version of it.
    ///
    /// # Examples
    ///
    /// ```
    /// # futures::executor::block_on(async {
    /// use futures::{stream::{StreamExt, self}, future::join};
    /// use futures_rx::{Notification, RxExt};
    ///
    /// let stream = stream::iter(0..=3);
    /// let stream = stream.share_replay();
    ///
    /// stream.clone().collect::<Vec<_>>().await; // consume all events beforehand
    ///
    /// let sub_stream_a = stream.clone().map(|event| *event); // an event is Event here, wrapping a ref counted value
    /// let sub_stream_b = stream.clone().map(|event| *event); // which we can just deref in this case to i32
    ///
    /// assert_eq!(
    ///     (vec![0, 1, 2, 3], vec![0, 1, 2, 3]),
    ///     join(
    ///         sub_stream_a.collect::<Vec<_>>(),
    ///         sub_stream_b.collect::<Vec<_>>()
    ///     )
    ///     .await
    /// );
    /// # });
    ///
    /// #
    /// ```
    fn share_replay(self) -> Shared<Self, ReplaySubject<Self::Item>>
    where
        Self: Sized,
    {
        assert_stream::<Event<Self::Item>, _>(Shared::new(self, ReplaySubject::new()))
    }

    /// Like `flat_map`, except that switched `Stream` is interrupted when the parent `Stream` emits a next event.
    ///
    /// Note that this function consumes the stream passed into it and returns a
    /// wrapped version of it.
    ///
    /// # Examples
    ///
    /// ```
    /// # futures::executor::block_on(async {
    /// use futures::stream::{self, StreamExt};
    /// use futures_rx::{Notification, RxExt};
    ///
    /// let stream = stream::iter(0..=3);
    /// let stream = stream.switch_map(|event| stream::iter([event + 10, event - 10]));
    ///
    /// assert_eq!(vec![10, 11, 12, 13, -7], stream.collect::<Vec<_>>().await);
    /// # });
    ///
    /// #
    /// ```
    fn switch_map<S: Stream, F: FnMut(Self::Item) -> S>(self, f: F) -> SwitchMap<Self, S, F>
    where
        Self: Sized,
    {
        assert_stream::<<F::Output as Stream>::Item, _>(SwitchMap::new(self, f))
    }

    /// Emits pairs of the previous and next events as a tuple.
    ///
    /// Note that this function consumes the stream passed into it and returns a
    /// wrapped version of it.
    ///
    /// The next value in the tuple is a value reference, and therefore wrapped inside an `Event` struct.
    /// An `Event` is a helper object for ref counted events.
    /// As the next event will also need to be emitted as the previous event in the next pair,
    /// it is first made available as next using a ref count - `Event`.
    ///
    /// # Examples
    ///
    /// ```
    /// # futures::executor::block_on(async {
    /// use futures::stream::{self, StreamExt};
    /// use futures_rx::{Notification, RxExt};
    ///
    /// let stream = stream::iter(0..=3);
    /// let stream = stream.pairwise();
    /// let stream = stream.map(|(prev, next)| (prev, *next)); // we can deref here to i32
    ///
    /// assert_eq!(vec![(0, 1), (1, 2), (2, 3)], stream.collect::<Vec<_>>().await);
    /// # });
    ///
    /// #
    /// ```
    fn pairwise(self) -> Pairwise<Self>
    where
        Self: Sized,
    {
        assert_stream::<(Self::Item, Event<Self::Item>), _>(Pairwise::new(self))
    }

    /// Delays events using a debounce time window.
    /// The event will emit when this window closes and when no other event
    /// was emitted while this window was open.
    ///
    /// The provided closure is executed over all elements of this stream as
    /// they are made available. It is executed inline with calls to
    /// [`poll_next`](Stream::poll_next).
    ///
    /// The debounce window resets on every newly emitted event.
    /// On next, the closure is invoked and a reference to the event is passed.
    /// The closure needs to return a `Future`, which represents the next debounce window over time.
    ///
    /// Note that this function consumes the stream passed into it and returns a
    /// wrapped version of it.
    fn debounce<Fut: Future, F: Fn(&Self::Item) -> Fut>(self, f: F) -> Debounce<Self, Fut, F>
    where
        Self: Sized,
    {
        assert_stream::<Self::Item, _>(Debounce::new(self, f))
    }

    /// Creates a new interval from the closure, whenever a new event is emitted from the parent `Stream`.
    /// This event is immediately emitted, however for as long as the interval is now open, no
    /// subsequent events will be emitted.
    ///
    /// When the interval closes and the parent `Stream` emits a new event, this
    /// process repeats.
    ///
    /// The provided closure is executed over all elements of this stream as
    /// they are made available. It is executed inline with calls to
    /// [`poll_next`](Stream::poll_next).
    ///
    /// Note that this function consumes the stream passed into it and returns a
    /// wrapped version of it.
    fn throttle<Fut: Future, F: Fn(&Self::Item) -> Fut>(self, f: F) -> Throttle<Self, Fut, F>
    where
        Self: Sized,
    {
        assert_stream::<Self::Item, _>(Throttle::new(self, f))
    }

    /// Creates chunks of buffered data.
    ///
    /// The provided closure is executed over all elements of this stream as
    /// they are made available. It is executed inline with calls to
    /// [`poll_next`](Stream::poll_next).
    ///
    /// You can use a reference to the current event, or the count of the current buffer
    /// to determine when a chunk should close and emit next.
    ///
    /// Note that this function consumes the stream passed into it and returns a
    /// wrapped version of it.
    ///
    /// # Examples
    ///
    /// ```
    /// # futures::executor::block_on(async {
    /// use std::collections::VecDeque;
    ///
    /// use futures::stream::{self, StreamExt};
    /// use futures_rx::RxExt;
    ///
    /// let stream = stream::iter(0..9);
    /// let stream = stream.buffer(|_, count| async move { count == 3 });
    ///
    /// assert_eq!(
    ///     vec![
    ///         VecDeque::from_iter([0, 1, 2]),
    ///         VecDeque::from_iter([3, 4, 5]),
    ///         VecDeque::from_iter([6, 7, 8])
    ///     ],
    ///     stream.collect::<Vec<_>>().await
    /// );
    /// # });
    ///
    /// #
    /// ```
    fn buffer<Fut: Future<Output = bool>, F: Fn(&Self::Item, usize) -> Fut>(
        self,
        f: F,
    ) -> Buffer<Self, Fut, F>
    where
        Self: Sized,
    {
        assert_stream::<VecDeque<Self::Item>, _>(Buffer::new(self, f))
    }

    /// Creates chunks of buffered data as new `Stream`s.
    ///
    /// The provided closure is executed over all elements of this stream as
    /// they are made available. It is executed inline with calls to
    /// [`poll_next`](Stream::poll_next).
    ///
    /// You can use a reference to the current event, or the count of the current buffer
    /// to determine when a chunk should close and emit next.
    ///
    /// Note that this function consumes the stream passed into it and returns a
    /// wrapped version of it.
    ///
    /// # Examples
    ///
    /// ```
    /// # futures::executor::block_on(async {
    /// use futures::stream::{self, StreamExt};
    /// use futures_rx::RxExt;
    ///
    /// let stream = stream::iter(0..9);
    /// let stream = stream.window(|_, count| async move { count == 3 }).flat_map(|it| it);
    ///
    /// assert_eq!(vec![0, 1, 2, 3, 4, 5, 6, 7, 8], stream.collect::<Vec<_>>().await);
    /// # });
    ///
    /// #
    /// ```
    fn window<Fut: Future<Output = bool>, F: Fn(&Self::Item, usize) -> Fut>(
        self,
        f: F,
    ) -> Window<Self, Fut, F>
    where
        Self: Sized,
    {
        assert_stream::<Iter<IntoIter<Self::Item>>, _>(Window::new(self, f))
    }

    /// Ensures that all emitted events are unique.
    /// Events are required to implement `Hash`.
    ///
    /// Note that this function consumes the stream passed into it and returns a
    /// wrapped version of it.
    ///
    /// # Examples
    ///
    /// ```
    /// # futures::executor::block_on(async {
    /// use futures::stream::{self, StreamExt};
    /// use futures_rx::RxExt;
    ///
    /// let stream = stream::iter([1, 2, 1, 3, 2, 2, 1, 4]);
    /// let stream = stream.distinct();
    ///
    /// assert_eq!(vec![1, 2, 3, 4], stream.collect::<Vec<_>>().await);
    /// # });
    ///
    /// #
    /// ```
    fn distinct(self) -> Distinct<Self>
    where
        Self: Sized,
        Self::Item: Hash,
    {
        assert_stream::<Self::Item, _>(Distinct::new(self))
    }

    /// Ensures that all emitted events are unique within immediate sequence.
    /// Events are required to implement `Hash`.
    ///
    /// Note that this function consumes the stream passed into it and returns a
    /// wrapped version of it.
    ///
    /// # Examples
    ///
    /// ```
    /// # futures::executor::block_on(async {
    /// use futures::stream::{self, StreamExt};
    /// use futures_rx::RxExt;
    ///
    /// let stream = stream::iter([1, 1, 1, 2, 2, 2, 3, 1, 1]);
    /// let stream = stream.distinct_until_changed();
    ///
    /// assert_eq!(vec![1, 2, 3, 1], stream.collect::<Vec<_>>().await);
    /// # });
    ///
    /// #
    /// ```
    fn distinct_until_changed(self) -> DistinctUntilChanged<Self>
    where
        Self: Sized,
        Self::Item: Hash,
    {
        assert_stream::<Self::Item, _>(DistinctUntilChanged::new(self))
    }

    /// Converts all events of a `Stream` into `Notification` events.
    /// When the `Stream` is done, it will first emit a final `Notification::Complete` event.
    ///
    /// Note that this function consumes the stream passed into it and returns a
    /// wrapped version of it.
    ///
    /// # Examples
    ///
    /// ```
    /// # futures::executor::block_on(async {
    /// use futures::stream::{self, StreamExt};
    /// use futures_rx::{Notification, RxExt};
    ///
    /// let stream = stream::iter(0..=3);
    /// let stream = stream.materialize();
    ///
    /// assert_eq!(
    ///     vec![
    ///         Notification::Next(0),
    ///         Notification::Next(1),
    ///         Notification::Next(2),
    ///         Notification::Next(3),
    ///         Notification::Complete
    ///     ],
    ///     stream.collect::<Vec<_>>().await
    /// );
    /// # });
    ///
    /// #
    /// ```
    fn materialize(self) -> Materialize<Self>
    where
        Self: Sized,
    {
        assert_stream::<Notification<Self::Item>, _>(Materialize::new(self))
    }

    /// The inverse of materialize.
    /// Use this transformer to translate a `Stream` emitting `Notification` events back
    /// into a `Stream` emitting original events.
    ///
    /// Note that this function consumes the stream passed into it and returns a
    /// wrapped version of it.
    ///
    /// # Examples
    ///
    /// ```
    /// # futures::executor::block_on(async {
    /// use futures::stream::{self, StreamExt};
    /// use futures_rx::RxExt;
    ///
    /// let stream = stream::iter(0..=3);
    /// let stream = stream.materialize().dematerialize();
    ///
    /// assert_eq!(vec![0, 1, 2, 3], stream.collect::<Vec<_>>().await);
    /// # });
    ///
    /// #
    /// ```
    fn dematerialize<T>(self) -> Dematerialize<Self, T>
    where
        Self: Stream<Item = Notification<T>> + Sized,
    {
        assert_stream::<T, _>(Dematerialize::new(self))
    }

    /// Delays emitting events using an initial time window, provided by a closure.
    ///
    /// Note that this function consumes the stream passed into it and returns a
    /// wrapped version of it.
    ///
    /// # Examples
    ///
    /// ```
    /// # futures::executor::block_on(async {
    /// use futures::stream::{self, StreamExt};
    /// use futures_rx::RxExt;
    ///
    /// let stream = stream::iter(0..=3);
    /// let stream = stream.delay(|| async { /* return delayed over time */ });
    ///
    /// assert_eq!(vec![0, 1, 2, 3], stream.collect::<Vec<_>>().await);
    /// # });
    ///
    /// #
    /// ```
    fn delay<Fut: Future, F: Fn() -> Fut>(self, f: F) -> Delay<Self, Fut, F>
    where
        Self: Sized,
    {
        assert_stream::<Self::Item, _>(Delay::new(self, f))
    }

    /// Acts just like a `CombineLatest2`, where every next event is a tuple pair
    /// containing the last emitted events from both `Stream`s.
    ///
    /// Note that this function consumes the stream passed into it and returns a
    /// wrapped version of it.
    ///
    /// # Examples
    ///
    /// ```
    /// # futures::executor::block_on(async {
    /// use futures::stream::{self, StreamExt};
    /// use futures_rx::RxExt;
    ///
    /// let stream = stream::iter(0..=3);
    /// let stream = stream.with_latest_from(stream::iter(0..=3));
    ///
    /// assert_eq!(vec![(0, 0), (1, 1), (2, 2), (3, 3)], stream.collect::<Vec<_>>().await);
    /// # });
    ///
    /// #
    /// ```
    fn with_latest_from<S: Stream>(self, stream: S) -> CombineLatest2<Self, S, Self::Item, S::Item>
    where
        Self: Sized,
        Self::Item: ToOwned<Owned = Self::Item>,
        S::Item: ToOwned<Owned = S::Item>,
    {
        assert_stream::<(Self::Item, S::Item), _>(CombineLatest2::new(self, stream))
    }
}

pub(crate) fn assert_stream<T, S>(stream: S) -> S
where
    S: Stream<Item = T>,
{
    stream
}