/
observable.rs
2061 lines (1910 loc) · 54.7 KB
/
observable.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
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#![macro_use]
mod trivial;
use std::hash::*;
use std::sync::Arc;
pub use trivial::*;
mod from_iter;
pub use from_iter::{from_iter, repeat};
pub mod of;
pub use of::{of, of_fn, of_option, of_result};
pub(crate) mod from_future;
pub use from_future::{from_future, from_future_result};
pub(crate) mod from_stream;
pub(crate) mod from_stream_result;
pub use from_stream::from_stream;
pub use from_stream_result::from_stream_result;
pub mod interval;
pub use interval::{interval, interval_at};
pub(crate) mod connectable_observable;
pub use connectable_observable::ConnectableObservable;
pub mod from_fn;
pub use from_fn::*;
pub mod timer;
pub use timer::{timer, timer_at};
pub mod start;
pub use start::start;
use crate::prelude::*;
mod subscribe_item;
pub use subscribe_item::*;
mod defer;
pub use defer::*;
use crate::ops::collect::CollectOp;
use crate::ops::combine_latest::CombineLatestOpThread;
use crate::ops::complete_status::{CompleteStatus, StatusOp};
use crate::ops::delay::{DelayOpThreads, DelaySubscriptionOp};
use crate::ops::finalize::FinalizeOpThreads;
use crate::ops::future::{ObservableFuture, ObservableFutureObserver};
use crate::ops::merge::MergeOpThreads;
use crate::ops::merge_all::MergeAllOpThreads;
use crate::ops::observe_on::ObserveOnOpThreads;
use crate::ops::on_complete::OnCompleteOp;
use crate::ops::on_error::OnErrorOp;
use crate::ops::ref_count::{ShareOp, ShareOpThreads};
use crate::ops::sample::SampleOpThreads;
use crate::ops::skip_until::SkipUntilOpThreads;
use crate::ops::stream::{ObservableStream, ObservableStreamObserver};
use crate::ops::take_until::TakeUntilOpThreads;
use crate::ops::timestamp::TimestampOp;
use crate::ops::with_latest_from::WithLatestFromOpThreads;
use crate::ops::zip::ZipOpThreads;
use crate::ops::FlatMapOpThreads;
pub use ops::box_it::BoxIt;
use crate::ops::default_if_empty::DefaultIfEmptyOp;
use crate::ops::distinct::{DistinctKeyOp, DistinctUntilKeyChangedOp};
use crate::ops::on_error_map::OnErrorMapOp;
use crate::ops::pairwise::PairwiseOp;
use crate::ops::tap::TapOp;
use ops::{
buffer::{
BufferOp, BufferWithCountOp, BufferWithCountOrTimerOp, BufferWithTimeOp,
},
combine_latest::CombineLatestOp,
contains::ContainsOp,
debounce::DebounceOp,
delay::DelayOp,
distinct::DistinctOp,
distinct::DistinctUntilChangedOp,
filter::FilterOp,
filter_map::FilterMapOp,
finalize::FinalizeOp,
group_by::GroupByOp,
last::LastOp,
map::MapOp,
map_to::MapToOp,
merge::MergeOp,
merge_all::MergeAllOp,
observe_on::ObserveOnOp,
sample::SampleOp,
scan::ScanOp,
skip::SkipOp,
skip_last::SkipLastOp,
skip_until::SkipUntilOp,
skip_while::SkipWhileOp,
start_with::StartWithOp,
subscribe_on::SubscribeOnOP,
take::TakeOp,
take_last::TakeLastOp,
take_until::TakeUntilOp,
take_while::TakeWhileOp,
throttle::{ThrottleEdge, ThrottleOp},
with_latest_from::WithLatestFromOp,
zip::ZipOp,
Accum, AverageOp, CountOp, FlatMapOp, MinMaxOp, ReduceOp, SumOp,
};
use std::ops::{Add, Mul};
#[cfg(test)]
pub mod fake_timer;
type ALLOp<S, F, Item> = DefaultIfEmptyOp<
TakeOp<FilterOp<MapOp<S, F, Item>, fn(&bool) -> bool>>,
bool,
>;
pub trait Observable<Item, Err, O>
where
O: Observer<Item, Err>,
{
type Unsub: Subscription;
fn actual_subscribe(self, observer: O) -> Self::Unsub;
}
pub trait ObservableExt<Item, Err>: Sized {
/// emit only the first item emitted by an Observable
#[inline]
fn first(self) -> TakeOp<Self> {
self.take(1)
}
/// emit only the first item emitted by an Observable
fn first_or(self, default: Item) -> DefaultIfEmptyOp<TakeOp<Self>, Item> {
DefaultIfEmptyOp::new(self.first(), default)
}
/// Emit only the last final item emitted by a source observable or a
/// default item given.
///
/// Completes right after emitting the single item. Emits error when
/// source observable emits it.
///
/// # Examples
///
/// ```
/// use rxrust::prelude::*;
///
/// observable::empty()
/// .last_or(1234)
/// .subscribe(|v| println!("{}", v));
///
/// // print log:
/// // 1234
/// ```
#[inline]
fn last_or(
self,
default: Item,
) -> DefaultIfEmptyOp<LastOp<Self, Item>, Item> {
DefaultIfEmptyOp::new(self.last(), default)
}
/// Emit only item n (0-indexed) emitted by an Observable
#[inline]
fn element_at(self, nth: usize) -> TakeOp<SkipOp<Self>> {
TakeOp::new(self.skip(nth), 1)
}
/// Do not emit any items from an Observable but mirror its termination
/// notification
#[inline]
fn ignore_elements(self) -> FilterOp<Self, fn(&Item) -> bool> {
fn always_false<Item>(_: &Item) -> bool {
false
}
self.filter(always_false as fn(&Item) -> bool)
}
/// Determine whether all items emitted by an Observable meet some criteria
#[inline]
fn all<F>(self, pred: F) -> ALLOp<Self, F, Item>
where
F: Fn(Item) -> bool,
{
fn not(b: &bool) -> bool {
!b
}
let map: MapOp<Self, F, Item> = MapOp::new(self, pred);
let filter_map = FilterOp {
source: map,
filter: not as fn(&bool) -> bool,
};
let take = TakeOp::new(filter_map, 1);
DefaultIfEmptyOp::new(take, true)
}
/// Determine whether an Observable emits a particular item or not
fn contains(self, target: Item) -> ContainsOp<Self, Item> {
ContainsOp { source: self, target }
}
/// Emits only last final item emitted by a source observable.
///
/// Completes right after emitting the single last item, or when source
/// observable completed, being an empty one. Emits error when source
/// observable emits it.
///
/// # Examples
///
/// ```
/// use rxrust::prelude::*;
///
/// observable::from_iter(0..100)
/// .last()
/// .subscribe(|v| println!("{}", v));
///
/// // print log:
/// // 99
/// ```
#[inline]
fn last(self) -> LastOp<Self, Item> {
LastOp { source: self, last: None }
}
/// Call a function when observable completes, errors or is unsubscribed from.
#[inline]
fn finalize<F>(self, f: F) -> FinalizeOp<Self, F>
where
F: FnMut(),
{
FinalizeOp::new(self, f)
}
/// A threads safe version of `finalize`
fn finalize_threads<F>(self, f: F) -> FinalizeOpThreads<Self, F>
where
F: FnMut(),
{
FinalizeOpThreads::new(self, f)
}
/// Creates an Observable that combines all the emissions from Observables
/// that get emitted from an Observable.
///
/// # Example
///
/// ```
/// # use rxrust::prelude::*;
/// let mut source = Subject::default();
/// let numbers = Subject::default();
/// // create a even stream by filter
/// let even = numbers.clone().filter((|v| *v % 2 == 0) as fn(&i32) -> bool);
/// // create an odd stream by filter
/// let odd = numbers.clone().filter((|v| *v % 2 != 0) as fn(&i32) -> bool);
///
/// // merge odd and even stream again
/// let out = source.clone().flatten();
///
/// source.next(even);
/// source.next(odd);
///
/// // attach observers
/// out.subscribe(|v: i32| println!("{} ", v));
/// ```
#[inline]
fn flatten<'a, Item2, Err2>(self) -> MergeAllOp<'a, Self, Item>
where
Item: ObservableExt<Item2, Err2>,
{
MergeAllOp::new(self, usize::MAX)
}
/// A threads safe version of `flatten`
#[inline]
fn flatten_threads<Item2, Err2>(self) -> MergeAllOpThreads<Self, Item>
where
Item: ObservableExt<Item2, Err2>,
{
MergeAllOpThreads::new(self, usize::MAX)
}
/// Applies given function to each item emitted by this Observable, where
/// that function returns an Observable that itself emits items. It then
/// merges the emissions of these resulting Observables, emitting these
/// merged results as its own sequence.
#[inline]
fn flat_map<'a, V, Item2, F>(self, f: F) -> FlatMapOp<'a, Self, V, F, Item>
where
F: FnMut(Item) -> V,
MapOp<Self, F, Item>: ObservableExt<V, Err>,
V: ObservableExt<Item2, Err>,
{
self.map(f).merge_all(usize::MAX)
}
#[inline]
fn concat_map<'a, V, Item2, F>(self, f: F) -> FlatMapOp<'a, Self, V, F, Item>
where
F: FnMut(Item) -> V,
MapOp<Self, F, Item>: ObservableExt<V, Err>,
V: ObservableExt<Item2, Err>,
{
self.map(f).concat_all()
}
#[inline]
fn flat_map_threads<V, Item2, F>(
self,
f: F,
) -> FlatMapOpThreads<Self, V, F, Item>
where
F: FnMut(Item) -> V,
MapOp<Self, F, Item>: ObservableExt<V, Err>,
V: ObservableExt<Item2, Err>,
{
self.map(f).merge_all_threads(usize::MAX)
}
#[inline]
fn concat_map_threads<V, Item2, F>(
self,
f: F,
) -> FlatMapOpThreads<Self, V, F, Item>
where
F: FnMut(Item) -> V,
MapOp<Self, F, Item>: ObservableExt<V, Err>,
V: ObservableExt<Item2, Err>,
{
self.map(f).concat_all_threads()
}
/// Groups items emitted by the source Observable into Observables.
/// Each emitted Observable emits items matching the key returned
/// by the discriminator function.
///
/// # Example
///
/// ```
/// use rxrust::prelude::*;
///
/// #[derive(Clone)]
/// struct Person {
/// name: String,
/// age: u32,
/// }
///
/// observable::from_iter([
/// Person{ name: String::from("John"), age: 26 },
/// Person{ name: String::from("Anne"), age: 28 },
/// Person{ name: String::from("Gregory"), age: 24 },
/// Person{ name: String::from("Alice"), age: 28 },
/// ])
/// .group_by::<_,_,Subject<_,_>>(|person: &Person| person.age)
/// .flat_map(|group| group.reduce(|acc, person: Person| format!("{} {}", acc, person.name)))
/// .subscribe(|result| println!("{}", result));
///
/// // Prints:
/// // John
/// // Anne Alice
/// // Gregory
/// ```
#[inline]
fn group_by<D, Key, Subject>(self, discr: D) -> GroupByOp<Self, D, Subject>
where
D: FnMut(&Item) -> Key,
Key: Hash + Eq + Clone,
Subject: Clone + Default + Observer<Item, Err>,
{
GroupByOp::new(self, discr)
}
/// Creates a new stream which calls a closure on each element and uses
/// its return as the value.
#[inline]
fn map<B, F>(self, f: F) -> MapOp<Self, F, Item>
where
F: FnMut(Item) -> B,
{
MapOp::new(self, f)
}
/// Creates a new stream which calls a closure on each error and uses
/// its return as emitted error.
#[inline]
fn on_error_map<B, F>(self, f: F) -> OnErrorMapOp<Self, F, Err>
where
F: FnMut(Err) -> B,
{
OnErrorMapOp::new(self, f)
}
/// Maps emissions to a constant value.
#[inline]
fn map_to<B>(self, value: B) -> MapToOp<Self, B, Item> {
MapToOp::new(self, value)
}
/// Creates a new stream which maps each element to a tuple of the element
/// and the time that it was observed.
#[inline]
fn timestamp(self) -> TimestampOp<Self, Item> {
fn timestamp<Item>(v: Item) -> (Item, Instant) {
(v, Instant::now())
}
self.map(timestamp)
}
/// combine two Observables into one by merging their emissions
///
/// # Example
///
/// ```
/// # use rxrust::prelude::*;
/// let numbers = Subject::default();
/// // create a even stream by filter
/// let even = numbers.clone().filter(|v| *v % 2 == 0);
/// // create an odd stream by filter
/// let odd = numbers.clone().filter(|v| *v % 2 != 0);
///
/// // merge odd and even stream again
/// let merged = even.merge(odd);
///
/// // attach observers
/// merged.subscribe(|v: &i32| println!("{} ", v));
/// ```
#[inline]
fn merge<S>(self, other: S) -> MergeOp<Self, S>
where
S: ObservableExt<Item, Err>,
{
MergeOp::new(self, other)
}
/// A threads safe version of `merge`
#[inline]
fn merge_threads<S>(self, other: S) -> MergeOpThreads<Self, S>
where
S: ObservableExt<Item, Err>,
{
MergeOpThreads::new(self, other)
}
/// Converts a higher-order Observable into a first-order Observable which
/// concurrently delivers all values that are emitted on the inner
/// Observables.
///
/// # Example
///
/// ```
/// # use rxrust::prelude::*;
/// # use futures::executor::LocalPool;
/// # use std::time::Duration;
/// let mut local = LocalPool::new();
/// observable::from_iter(
/// (0..3)
/// .map(|_| interval(Duration::from_millis(1), local.spawner()).take(5)),
/// )
/// .merge_all(2)
/// .subscribe(move |i| println!("{}", i));
/// local.run();
/// ```
#[inline]
fn merge_all<'a, Item2>(self, concurrent: usize) -> MergeAllOp<'a, Self, Item>
where
Item: ObservableExt<Item2, Err>,
{
MergeAllOp::new(self, concurrent)
}
#[inline]
fn concat_all<'a, Item2>(self) -> MergeAllOp<'a, Self, Item>
where
Item: ObservableExt<Item2, Err>,
{
MergeAllOp::new(self, 1)
}
/// A threads safe version of `merge_all`
#[inline]
fn merge_all_threads<Item2>(
self,
concurrent: usize,
) -> MergeAllOpThreads<Self, Item>
where
Item: ObservableExt<Item2, Err>,
{
MergeAllOpThreads::new(self, concurrent)
}
#[inline]
fn concat_all_threads<Item2>(self) -> MergeAllOpThreads<Self, Item>
where
Item: ObservableExt<Item2, Err>,
{
MergeAllOpThreads::new(self, 1)
}
/// Emit only those items from an Observable that pass a predicate test
/// # Example
///
/// ```
/// use rxrust:: prelude::*;
///
/// let mut coll = vec![];
/// let coll_clone = coll.clone();
///
/// observable::from_iter(0..10)
/// .filter(|v| *v % 2 == 0)
/// .subscribe(|v| { coll.push(v); });
///
/// // only even numbers received.
/// assert_eq!(coll, vec![0, 2, 4, 6, 8]);
/// ```
#[inline]
fn filter<F>(self, filter: F) -> FilterOp<Self, F>
where
F: Fn(&Item) -> bool,
{
FilterOp { source: self, filter }
}
/// The closure must return an Option<T>. filter_map creates an iterator which
/// calls this closure on each element. If the closure returns Some(element),
/// then that element is returned. If the closure returns None, it will try
/// again, and call the closure on the next element, seeing if it will return
/// Some.
///
/// Why filter_map and not just filter and map? The key is in this part:
///
/// If the closure returns Some(element), then that element is returned.
///
/// In other words, it removes the Option<T> layer automatically. If your
/// mapping is already returning an Option<T> and you want to skip over Nones,
/// then filter_map is much, much nicer to use.
///
/// # Examples
///
/// ```
/// # use rxrust::prelude::*;
/// let mut res: Vec<i32> = vec![];
/// observable::from_iter(["1", "lol", "3", "NaN", "5"].iter())
/// .filter_map(|s: &&str| s.parse().ok())
/// .subscribe(|v| res.push(v));
///
/// assert_eq!(res, [1, 3, 5]);
/// ```
#[inline]
fn filter_map<F, OutputItem>(self, f: F) -> FilterMapOp<Self, F, Item>
where
F: FnMut(Item) -> Option<OutputItem>,
{
FilterMapOp::new(self, f)
}
/// Ignore the first `count` values emitted by the source Observable.
///
/// `skip` returns an Observable that ignore the first `count` values
/// emitted by the source Observable. If the source emits fewer than `count`
/// values then 0 of its values are emitted. After that, it completes,
/// regardless if the source completes.
///
/// # Example
/// Ignore the first 5 seconds of an infinite 1-second interval Observable
///
/// ```
/// # use rxrust::prelude::*;
///
/// observable::from_iter(0..10).skip(5).subscribe(|v| println!("{}", v));
/// // print logs:
/// // 6
/// // 7
/// // 8
/// // 9
/// // 10
/// ```
#[inline]
fn skip(self, count: usize) -> SkipOp<Self> {
SkipOp::new(self, count)
}
/// Discard items emitted by an Observable until a second Observable emits an item
///
/// # Example
/// Ignore the numbers in the 0-10 range until the Observer emits 5 and trigger
/// the notify observable.
///
/// ```
/// # use rxrust::prelude::*;
///
/// let mut items = vec![];
/// let notifier = Subject::<(), ()>::default();
/// let mut c_notifier = notifier.clone();
/// observable::from_iter(0..10)
/// .tap(move |v| {
/// if v == &5 {
/// c_notifier.next(());
/// }
/// })
/// .skip_until(notifier)
/// .subscribe(|v| items.push(v));
///
/// assert_eq!((5..10).collect::<Vec<i32>>(), items);
/// ```
#[inline]
fn skip_until<NotifyItem, NotifyErr, Other>(
self,
notifier: Other,
) -> SkipUntilOp<Self, Other, NotifyItem, NotifyErr>
where
Other: ObservableExt<NotifyItem, NotifyErr>,
{
SkipUntilOp::new(self, notifier)
}
/// A threads safe version of `skip_until_threads`
#[inline]
fn skip_until_threads<NotifyItem, NotifyErr, Other>(
self,
notifier: Other,
) -> SkipUntilOpThreads<Self, Other, NotifyItem, NotifyErr>
where
Other: ObservableExt<NotifyItem, NotifyErr>,
{
SkipUntilOpThreads::new(self, notifier)
}
/// Discard items emitted by an Observable until a specified condition becomes false
///
///
/// # Example
/// Suppress the first 5 items of an infinite 1-second interval Observable
///
/// ```
/// # use rxrust::prelude::*;
///
/// observable::from_iter(0..10)
/// .skip_while(|v| v < &5)
/// .subscribe(|v| println!("{}", v));
///
/// // print logs:
/// // 5
/// // 6
/// // 7
/// // 8
/// // 9
/// ```
#[inline]
fn skip_while<F>(self, predicate: F) -> SkipWhileOp<Self, F>
where
F: FnMut(&Item) -> bool,
{
SkipWhileOp { source: self, predicate }
}
/// Ignore the last `count` values emitted by the source Observable.
///
/// `skip_last` returns an Observable that ignore the last `count` values
/// emitted by the source Observable. If the source emits fewer than `count`
/// values then 0 of its values are emitted.
/// It will not emit values until source Observable complete.
///
/// # Example
/// Skip the last 5 seconds of an infinite 1-second interval Observable
///
/// ```
/// # use rxrust::prelude::*;
///
/// observable::from_iter(0..10)
/// .skip_last(5)
/// .subscribe(|v| println!("{}", v));
///
/// // print logs:
/// // 0
/// // 1
/// // 2
/// // 3
/// // 4
/// ```
#[inline]
fn skip_last(self, count: usize) -> SkipLastOp<Self> {
SkipLastOp { source: self, count }
}
/// Emits only the first `count` values emitted by the source Observable.
///
/// `take` returns an Observable that emits only the first `count` values
/// emitted by the source Observable. If the source emits fewer than `count`
/// values then all of its values are emitted. After that, it completes,
/// regardless if the source completes.
///
/// # Example
/// Take the first 5 seconds of an infinite 1-second interval Observable
///
/// ```
/// # use rxrust::prelude::*;
///
/// observable::from_iter(0..10).take(5).subscribe(|v| println!("{}", v));
/// // print logs:
/// // 0
/// // 1
/// // 2
/// // 3
/// // 4
/// ```
///
#[inline]
fn take(self, count: usize) -> TakeOp<Self> {
TakeOp::new(self, count)
}
/// Emits the values emitted by the source Observable until a `notifier`
/// Observable emits a value.
///
/// `take_until` subscribes and begins mirroring the source Observable. It
/// also monitors a second Observable, `notifier` that you provide. If the
/// `notifier` emits a value, the output Observable stops mirroring the source
/// Observable and completes. If the `notifier` doesn't emit any value and
/// completes then `take_until` will pass all values.
#[inline]
fn take_until<Notify, NotifyItem, NotifyErr>(
self,
notifier: Notify,
) -> TakeUntilOp<Self, Notify, NotifyItem, NotifyErr> {
TakeUntilOp::new(self, notifier)
}
#[inline]
fn take_until_threads<Notify, NotifyItem, NotifyErr>(
self,
notifier: Notify,
) -> TakeUntilOpThreads<Self, Notify, NotifyItem, NotifyErr> {
TakeUntilOpThreads::new(self, notifier)
}
/// Emits values while result of an callback is true.
///
/// `take_while` returns an Observable that emits values while result of an
/// callback is true emitted by the source Observable.
/// It will not emit values until source Observable complete.
///
/// # Example
/// Take the first 5 seconds of an infinite 1-second interval Observable
///
/// ```
/// # use rxrust::prelude::*;
///
/// observable::from_iter(0..10)
/// .take_while(|v| v < &5)
/// .subscribe(|v| println!("{}", v));
/// // print logs:
/// // 0
/// // 1
/// // 2
/// // 3
/// // 4
/// ```
///
#[inline]
fn take_while<F>(self, callback: F) -> TakeWhileOp<Self, F>
where
F: FnMut(&Item) -> bool,
{
TakeWhileOp { source: self, callback, inclusive: false }
}
/// Emits values while result of an callback is true and the last one that
/// causes the callback to return false.
///
/// # Example
/// Take the first 5 seconds of an infinite 1-second interval Observable
///
/// ```
/// # use rxrust::prelude::*;
///
/// observable::from_iter(0..10)
/// .take_while_inclusive(|v| v < &4)
/// .subscribe(|v| println!("{}", v));
/// // print logs:
/// // 0
/// // 1
/// // 2
/// // 3
/// // 4
/// ```
///
#[inline]
fn take_while_inclusive<F>(self, callback: F) -> TakeWhileOp<Self, F>
where
F: FnMut(&Item) -> bool,
{
TakeWhileOp { source: self, callback, inclusive: true }
}
/// Emits only the last `count` values emitted by the source Observable.
///
/// `take_last` returns an Observable that emits only the last `count` values
/// emitted by the source Observable. If the source emits fewer than `count`
/// values then all of its values are emitted.
/// It will not emit values until source Observable complete.
///
/// # Example
/// Take the last 5 seconds of an infinite 1-second interval Observable
///
/// ```
/// # use rxrust::prelude::*;
///
/// observable::from_iter(0..10)
/// .take_last(5)
/// .subscribe(|v| println!("{}", v));
/// // print logs:
/// // 5
/// // 6
/// // 7
/// // 8
/// // 9
/// ```
///
#[inline]
fn take_last(self, count: usize) -> TakeLastOp<Self> {
TakeLastOp { source: self, count }
}
/// Emits item it has most recently emitted since the previous sampling
///
///
/// It will emit values when sampling observable complete.
///
/// #Example
/// Sampling every 5ms of an infinite 1ms interval Observable
/// ```
/// use rxrust::prelude::*;
/// use std::time::Duration;
/// use futures::executor::LocalPool;
///
/// let mut local_scheduler = LocalPool::new();
/// let spawner = local_scheduler.spawner();
/// observable::interval(Duration::from_millis(2), spawner.clone())
/// .sample(observable::interval(Duration::from_millis(5), spawner))
/// .take(5)
/// .subscribe(move |v| println!("{}", v));
///
/// local_scheduler.run();
/// // print logs:
/// // 1
/// // 4
/// // 6
/// // 9
/// // ...
/// ```
#[inline]
fn sample<Sample, SampleItem, SampleErr>(
self,
sampling: Sample,
) -> SampleOp<Self, Sample, SampleItem>
where
Sample: ObservableExt<SampleItem, SampleErr>,
{
SampleOp::new(self, sampling)
}
/// A threads safe version of `sample`
#[inline]
fn sample_threads<Sample, SampleItem, SampleErr>(
self,
sampling: Sample,
) -> SampleOpThreads<Self, Sample, SampleItem>
where
Sample: ObservableExt<SampleItem, SampleErr>,
{
SampleOpThreads::new(self, sampling)
}
/// The Scan operator applies a function to the first item emitted by the
/// source observable and then emits the result of that function as its
/// own first emission. It also feeds the result of the function back into
/// the function along with the second item emitted by the source observable
/// in order to generate its second emission. It continues to feed back its
/// own subsequent emissions along with the subsequent emissions from the
/// source Observable in order to create the rest of its sequence.
///
/// Applies a binary operator closure to each item emitted from source
/// observable and emits successive values.
///
/// Completes when source observable completes.
/// Emits error when source observable emits it.
///
/// This version starts with an user-specified initial value for when the
/// binary operator is called with the first item processed.
///
/// # Arguments
///
/// * `initial_value` - An initial value to start the successive accumulations
/// from.
/// * `binary_op` - A closure or function acting as a binary operator.
///
/// # Examples
///
/// ```
/// use rxrust::prelude::*;
///
/// observable::from_iter(vec![1, 1, 1, 1, 1])
/// .scan_initial(100, |acc, v| acc + v)
/// .subscribe(|v| println!("{}", v));
///
/// // print log:
/// // 101
/// // 102
/// // 103
/// // 104
/// // 105
/// ```
#[inline]
fn scan_initial<OutputItem, BinaryOp>(
self,
initial_value: OutputItem,
binary_op: BinaryOp,
) -> ScanOp<Self, BinaryOp, OutputItem, Item>
where
BinaryOp: Fn(OutputItem, Item) -> OutputItem,
OutputItem: Clone,
{
ScanOp::new(self, binary_op, initial_value)
}
/// Works like [`scan_initial`](Observable::scan_initial) but starts with a
/// value defined by a [`Default`] trait for the first argument `binary_op`
/// operator operates on.
///
/// # Arguments
///
/// * `binary_op` - A closure or function acting as a binary operator.
#[inline]
fn scan<OutputItem, BinaryOp>(
self,
binary_op: BinaryOp,
) -> ScanOp<Self, BinaryOp, OutputItem, Item>
where
BinaryOp: Fn(OutputItem, Item) -> OutputItem,
OutputItem: Default + Clone,
{
self.scan_initial(OutputItem::default(), binary_op)
}
/// Apply a function to each item emitted by an observable, sequentially,
/// and emit the final value, after source observable completes.
///
/// Emits error when source observable emits it.
///
/// # Arguments
///
/// * `initial` - An initial value to start the successive reduction from.
/// * `binary_op` - A closure acting as a binary (folding) operator.
///
/// # Examples
///
/// ```
/// use rxrust::prelude::*;
///
/// observable::from_iter(vec![1, 1, 1, 1, 1])
/// .reduce_initial(100, |acc, v| acc + v)
/// .subscribe(|v| println!("{}", v));
///
/// // print log:
/// // 105
/// ```
#[inline]
fn reduce_initial<OutputItem, BinaryOp>(
self,
initial: OutputItem,
binary_op: BinaryOp,
) -> ReduceOp<Self, BinaryOp, OutputItem, Item>
where
BinaryOp: Fn(OutputItem, Item) -> OutputItem,
OutputItem: Clone,
{
// realised as a composition of `scan`, and `last`
let scan = self.scan_initial(initial.clone(), binary_op);
let last = LastOp { source: scan, last: None };
DefaultIfEmptyOp::new(last, initial)
}
/// Works like [`reduce_initial`](Observable::reduce_initial) but starts with
/// a value defined by a [`Default`] trait for the first argument `f`
/// operator operates on.
///
/// # Arguments
///
/// * `binary_op` - A closure acting as a binary operator.
#[inline]
fn reduce<OutputItem, BinaryOp>(
self,
binary_op: BinaryOp,
) -> ReduceOp<Self, BinaryOp, OutputItem, Item>
where
BinaryOp: Fn(OutputItem, Item) -> OutputItem,
OutputItem: Default + Clone,