1 package com.github.davidmoten.rx;
2
3 import java.nio.charset.CharsetDecoder;
4 import java.util.ArrayList;
5 import java.util.Arrays;
6 import java.util.Collection;
7 import java.util.Comparator;
8 import java.util.HashSet;
9 import java.util.List;
10 import java.util.Map;
11 import java.util.Set;
12 import java.util.concurrent.TimeUnit;
13 import java.util.concurrent.atomic.AtomicInteger;
14 import java.util.regex.Pattern;
15
16 import com.github.davidmoten.rx.StateMachine.Completion;
17 import com.github.davidmoten.rx.StateMachine.Transition;
18 import com.github.davidmoten.rx.buffertofile.DataSerializer;
19 import com.github.davidmoten.rx.buffertofile.DataSerializers;
20 import com.github.davidmoten.rx.buffertofile.Options;
21 import com.github.davidmoten.rx.internal.operators.OnSubscribeDoOnEmpty;
22 import com.github.davidmoten.rx.internal.operators.OnSubscribeMapLast;
23 import com.github.davidmoten.rx.internal.operators.OperatorBufferPredicateBoundary;
24 import com.github.davidmoten.rx.internal.operators.OperatorBufferToFile;
25 import com.github.davidmoten.rx.internal.operators.OperatorDoOnNth;
26 import com.github.davidmoten.rx.internal.operators.OperatorFromTransformer;
27 import com.github.davidmoten.rx.internal.operators.TransformerOnTerminateResume;
28 import com.github.davidmoten.rx.internal.operators.OperatorSampleFirst;
29 import com.github.davidmoten.rx.internal.operators.OperatorWindowMinMax;
30 import com.github.davidmoten.rx.internal.operators.OperatorWindowMinMax.Metric;
31 import com.github.davidmoten.rx.internal.operators.OrderedMerge;
32 import com.github.davidmoten.rx.internal.operators.TransformerDecode;
33 import com.github.davidmoten.rx.internal.operators.TransformerDelayFinalUnsubscribe;
34 import com.github.davidmoten.rx.internal.operators.TransformerLimitSubscribers;
35 import com.github.davidmoten.rx.internal.operators.TransformerOnBackpressureBufferRequestLimiting;
36 import com.github.davidmoten.rx.internal.operators.TransformerStateMachine;
37 import com.github.davidmoten.rx.internal.operators.TransformerStringSplit;
38 import com.github.davidmoten.rx.util.BackpressureStrategy;
39 import com.github.davidmoten.rx.util.MapWithIndex;
40 import com.github.davidmoten.rx.util.MapWithIndex.Indexed;
41 import com.github.davidmoten.rx.util.Pair;
42 import com.github.davidmoten.util.Optional;
43
44 import rx.Notification;
45 import rx.Observable;
46 import rx.Observable.Operator;
47 import rx.Observable.Transformer;
48 import rx.Observer;
49 import rx.Scheduler;
50 import rx.Scheduler.Worker;
51 import rx.Subscriber;
52 import rx.functions.Action0;
53 import rx.functions.Action1;
54 import rx.functions.Action2;
55 import rx.functions.Func0;
56 import rx.functions.Func1;
57 import rx.functions.Func2;
58 import rx.functions.Func3;
59 import rx.internal.util.RxRingBuffer;
60 import rx.observables.GroupedObservable;
61 import rx.schedulers.Schedulers;
62
63 public final class Transformers {
64
65 static final int DEFAULT_INITIAL_BATCH = 1;
66
67 public static <T, R> Operator<R, T> toOperator(
68 Func1<? super Observable<T>, ? extends Observable<R>> function) {
69 return OperatorFromTransformer.toOperator(function);
70 }
71
72 public static <T extends Number> Transformer<T, Statistics> collectStats() {
73 return new Transformer<T, Statistics>() {
74
75 @Override
76 public Observable<Statistics> call(Observable<T> o) {
77 return o.scan(Statistics.create(), Functions.collectStats());
78 }
79 };
80 }
81
82 public static <T, R extends Number> Transformer<T, Pair<T, Statistics>> collectStats(
83 final Func1<? super T, ? extends R> function) {
84 return new Transformer<T, Pair<T, Statistics>>() {
85
86 @Override
87 public Observable<Pair<T, Statistics>> call(Observable<T> source) {
88 return source.scan(Pair.create((T) null, Statistics.create()),
89 new Func2<Pair<T, Statistics>, T, Pair<T, Statistics>>() {
90 @Override
91 public Pair<T, Statistics> call(Pair<T, Statistics> pair, T t) {
92 return Pair.create(t, pair.b().add(function.call(t)));
93 }
94 }).skip(1);
95 }
96 };
97 }
98
99 public static <T extends Comparable<? super T>> Transformer<T, T> sort() {
100 return new Transformer<T, T>() {
101
102 @Override
103 public Observable<T> call(Observable<T> o) {
104 return o.toSortedList().flatMapIterable(Functions.<List<T>>identity());
105 }
106 };
107 }
108
109 public static <T> Transformer<T, T> sort(final Comparator<? super T> comparator) {
110 return new Transformer<T, T>() {
111
112 @Override
113 public Observable<T> call(Observable<T> o) {
114 return o.toSortedList(Functions.toFunc2(comparator))
115 .flatMapIterable(Functions.<List<T>>identity());
116 }
117 };
118 }
119
120 public static <T> Transformer<T, Set<T>> toSet() {
121 return new Transformer<T, Set<T>>() {
122
123 @Override
124 public Observable<Set<T>> call(Observable<T> o) {
125 return o.collect(new Func0<Set<T>>() {
126
127 @Override
128 public Set<T> call() {
129 return new HashSet<T>();
130 }
131 }, new Action2<Set<T>, T>() {
132
133 @Override
134 public void call(Set<T> set, T t) {
135 set.add(t);
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 public static <T> Transformer<T, Indexed<T>> mapWithIndex() {
172 return MapWithIndex.instance();
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 public static <State, In, Out> Transformer<In, Out> stateMachine(
230 Func0<State> initialStateFactory,
231 Func3<? super State, ? super In, ? super Subscriber<Out>, ? extends State> transition,
232 Func2<? super State, ? super Subscriber<Out>, Boolean> completion,
233 BackpressureStrategy backpressureStrategy) {
234 return TransformerStateMachine.<State, In, Out>create(initialStateFactory, transition,
235 completion, backpressureStrategy, DEFAULT_INITIAL_BATCH);
236 }
237
238 public static <State, In, Out> Transformer<In, Out> stateMachine(
239 Func0<State> initialStateFactory,
240 Func3<? super State, ? super In, ? super Subscriber<Out>, ? extends State> transition,
241 Func2<? super State, ? super Subscriber<Out>, Boolean> completion,
242 BackpressureStrategy backpressureStrategy, int initialRequest) {
243 return TransformerStateMachine.<State, In, Out>create(initialStateFactory, transition,
244 completion, backpressureStrategy, initialRequest);
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 public static <State, In, Out> Transformer<In, Out> stateMachine(
302 Func0<? extends State> initialStateFactory,
303 Func3<? super State, ? super In, ? super Subscriber<Out>, ? extends State> transition,
304 Func2<? super State, ? super Subscriber<Out>, Boolean> completion) {
305 return TransformerStateMachine.<State, In, Out>create(initialStateFactory, transition,
306 completion, BackpressureStrategy.BUFFER, DEFAULT_INITIAL_BATCH);
307 }
308
309 public static StateMachine.Builder stateMachine() {
310 return StateMachine.builder();
311 }
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333 public static final <T> Transformer<T, T> orderedMergeWith(final Observable<T> other,
334 final Comparator<? super T> comparator) {
335 @SuppressWarnings("unchecked")
336 Collection<Observable<T>> collection = Arrays.asList(other);
337 return orderedMergeWith(collection, comparator);
338 }
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360 public static final <T> Transformer<T, T> orderedMergeWith(
361 final Collection<Observable<T>> others, final Comparator<? super T> comparator) {
362 return new Transformer<T, T>() {
363
364 @Override
365 public Observable<T> call(Observable<T> source) {
366 List<Observable<T>> collection = new ArrayList<Observable<T>>();
367 collection.add(source);
368 collection.addAll(others);
369 return OrderedMerge.<T>create(collection, comparator, false);
370 }
371 };
372 }
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388 public static <T> Transformer<T, List<T>> toListUntilChanged() {
389 Func2<Collection<T>, T, Boolean> equal = HolderEquals.instance();
390 return toListWhile(equal);
391 }
392
393 private static class HolderEquals {
394 private static final Func2<Collection<Object>, Object, Boolean> INSTANCE = new Func2<Collection<Object>, Object, Boolean>() {
395 @Override
396 public Boolean call(Collection<Object> list, Object t) {
397 return list.isEmpty() || list.iterator().next().equals(t);
398 }
399 };
400
401 @SuppressWarnings("unchecked")
402 static <T> Func2<Collection<T>, T, Boolean> instance() {
403 return (Func2<Collection<T>, T, Boolean>) (Func2<?, ?, Boolean>) INSTANCE;
404 }
405 }
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425 public static <T> Transformer<T, List<T>> toListWhile(
426 final Func2<? super List<T>, ? super T, Boolean> condition) {
427
428 Func0<List<T>> initialState = new Func0<List<T>>() {
429 @Override
430 public List<T> call() {
431 return new ArrayList<T>();
432 }
433 };
434
435 Action2<List<T>, T> collect = new Action2<List<T>, T>() {
436
437 @Override
438 public void call(List<T> list, T n) {
439 list.add(n);
440 }
441 };
442 return collectWhile(initialState, collect, condition);
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 public static <T, R> Transformer<T, R> collectWhile(final Func0<R> factory,
473 final Action2<? super R, ? super T> collect,
474 final Func2<? super R, ? super T, Boolean> condition,
475 final Func1<? super R, Boolean> isEmpty) {
476 Func3<R, T, Observer<R>, R> transition = new Func3<R, T, Observer<R>, R>() {
477
478 @Override
479 public R call(R collection, T t, Observer<R> observer) {
480
481 if (condition.call(collection, t)) {
482 collect.call(collection, t);
483 return collection;
484 } else {
485 observer.onNext(collection);
486 R r = factory.call();
487 collect.call(r, t);
488 return r;
489 }
490 }
491
492 };
493 Func2<R, Observer<R>, Boolean> completionAction = new Func2<R, Observer<R>, Boolean>() {
494 @Override
495 public Boolean call(R collection, Observer<R> observer) {
496 if (!isEmpty.call(collection)) {
497 observer.onNext(collection);
498 }
499 return true;
500 }
501 };
502 return Transformers.stateMachine(factory, transition, completionAction);
503 }
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526 public static <T, R extends Collection<T>> Transformer<T, R> collectWhile(
527 final Func0<R> factory, final Action2<? super R, ? super T> collect) {
528 return collectWhile(factory, collect, HolderEquals.<T>instance());
529 }
530
531 public static <T, R extends Iterable<?>> Transformer<T, R> collectWhile(final Func0<R> factory,
532 final Action2<? super R, ? super T> collect,
533 final Func2<? super R, ? super T, Boolean> condition) {
534 Func1<R, Boolean> isEmpty = new Func1<R, Boolean>() {
535 @Override
536 public Boolean call(R collection) {
537 return !collection.iterator().hasNext();
538 }
539 };
540 return collectWhile(factory, collect, condition, isEmpty);
541 }
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556 public static <T> Transformer<T, T> doOnNext(final int n, final Action1<? super T> action) {
557 return new Transformer<T, T>() {
558 @Override
559 public Observable<T> call(Observable<T> o) {
560 return o.lift(OperatorDoOnNth.create(action, n));
561 }
562 };
563 }
564
565
566
567
568
569
570
571
572
573
574
575
576 public static <T> Transformer<T, T> doOnFirst(final Action1<? super T> action) {
577 return doOnNext(1, action);
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 public static <R, T> Transformer<T, R> ignoreElementsThen(final Observable<R> next) {
603 return new Transformer<T, R>() {
604
605 @SuppressWarnings("unchecked")
606 @Override
607 public Observable<R> call(Observable<T> source) {
608 return ((Observable<R>) (Observable<?>) source.ignoreElements()).concatWith(next);
609 }
610 };
611 }
612
613 public static <T> Transformer<String, String> split(String pattern) {
614 return TransformerStringSplit.split(pattern, null);
615 }
616
617 public static <T> Transformer<String, String> split(Pattern pattern) {
618 return TransformerStringSplit.split(null, pattern);
619 }
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636 public static Transformer<byte[], String> decode(final CharsetDecoder charsetDecoder) {
637 return TransformerDecode.decode(charsetDecoder);
638 }
639
640 public static <T> Transformer<T, T> limitSubscribers(AtomicInteger subscriberCount,
641 int maxSubscribers) {
642 return new TransformerLimitSubscribers<T>(subscriberCount, maxSubscribers);
643 }
644
645 public static <T> Transformer<T, T> limitSubscribers(int maxSubscribers) {
646 return new TransformerLimitSubscribers<T>(new AtomicInteger(), maxSubscribers);
647 }
648
649 public static <T> Transformer<T, T> cache(final long duration, final TimeUnit unit,
650 final Worker worker) {
651 return new Transformer<T, T>() {
652 @Override
653 public Observable<T> call(Observable<T> o) {
654 return Obs.cache(o, duration, unit, worker);
655 }
656 };
657 }
658
659 public static <T> Transformer<T, T> sampleFirst(final long duration, final TimeUnit unit) {
660 return sampleFirst(duration, unit, Schedulers.computation());
661 }
662
663 public static <T> Transformer<T, T> sampleFirst(final long duration, final TimeUnit unit,
664 final Scheduler scheduler) {
665 if (duration <= 0) {
666 throw new IllegalArgumentException("duration must be > 0");
667 }
668 return new Transformer<T, T>() {
669
670 @Override
671 public Observable<T> call(Observable<T> source) {
672 return source.lift(new OperatorSampleFirst<T>(duration, unit, scheduler));
673 }
674 };
675 }
676
677 public static <T> Transformer<T, T> onBackpressureBufferToFile() {
678 return onBackpressureBufferToFile(DataSerializers.<T>javaIO(), Schedulers.computation(),
679 Options.defaultInstance());
680 }
681
682 public static <T> Transformer<T, T> onBackpressureBufferToFile(
683 final DataSerializer<T> serializer) {
684 return onBackpressureBufferToFile(serializer, Schedulers.computation(),
685 Options.defaultInstance());
686 }
687
688 public static <T> Transformer<T, T> onBackpressureBufferToFile(
689 final DataSerializer<T> serializer, final Scheduler scheduler) {
690 return onBackpressureBufferToFile(serializer, scheduler, Options.defaultInstance());
691 }
692
693 public static <T> Transformer<T, T> onBackpressureBufferToFile(
694 final DataSerializer<T> serializer, final Scheduler scheduler, final Options options) {
695 return new Transformer<T, T>() {
696 @Override
697 public Observable<T> call(Observable<T> o) {
698 return o.lift(new OperatorBufferToFile<T>(serializer, scheduler, options));
699 }
700 };
701 }
702
703 public static <T> Transformer<T, T> windowMin(final int windowSize,
704 final Comparator<? super T> comparator) {
705 return new Transformer<T, T>() {
706 @Override
707 public Observable<T> call(Observable<T> o) {
708 return o.lift(new OperatorWindowMinMax<T>(windowSize, comparator, Metric.MIN));
709 }
710 };
711 }
712
713 public static <T extends Comparable<T>> Transformer<T, T> windowMax(final int windowSize) {
714 return windowMax(windowSize, Transformers.<T>naturalComparator());
715 }
716
717 public static <T> Transformer<T, T> windowMax(final int windowSize,
718 final Comparator<? super T> comparator) {
719 return new Transformer<T, T>() {
720 @Override
721 public Observable<T> call(Observable<T> o) {
722 return o.lift(new OperatorWindowMinMax<T>(windowSize, comparator, Metric.MAX));
723 }
724 };
725 }
726
727 public static <T extends Comparable<T>> Transformer<T, T> windowMin(final int windowSize) {
728 return windowMin(windowSize, Transformers.<T>naturalComparator());
729 }
730
731 private static class NaturalComparatorHolder {
732 static final Comparator<Comparable<Object>> INSTANCE = new Comparator<Comparable<Object>>() {
733
734 @Override
735 public int compare(Comparable<Object> o1, Comparable<Object> o2) {
736 return o1.compareTo(o2);
737 }
738 };
739 }
740
741 @SuppressWarnings("unchecked")
742 private static <T extends Comparable<T>> Comparator<T> naturalComparator() {
743 return (Comparator<T>) (Comparator<?>) NaturalComparatorHolder.INSTANCE;
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 public static <T, K, R> Transformer<T, GroupedObservable<K, R>> groupByEvicting(
814 final Func1<? super T, ? extends K> keySelector,
815 final Func1<? super T, ? extends R> elementSelector,
816 final Func1<Action1<K>, Map<K, Object>> evictingMapFactory) {
817 return new Transformer<T, GroupedObservable<K, R>>() {
818
819 @Override
820 public Observable<GroupedObservable<K, R>> call(Observable<T> o) {
821 return o.groupBy(keySelector, elementSelector, evictingMapFactory);
822 }
823 };
824 }
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843 public static <T> Transformer<T, T> delayFinalUnsubscribe(long duration, TimeUnit unit) {
844 return delayFinalUnsubscribe(duration, unit, Schedulers.computation());
845 }
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866 public static <T> Transformer<T, T> delayFinalUnsubscribe(long duration, TimeUnit unit,
867 Scheduler scheduler) {
868 return new TransformerDelayFinalUnsubscribe<T>(unit.toMillis(duration), scheduler);
869 }
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886 public static <T> Transformer<T, T> removePairs(
887 final Func1<? super T, Boolean> isCandidateForFirst,
888 final Func2<? super T, ? super T, Boolean> remove) {
889 return new Transformer<T, T>() {
890
891 @Override
892 public Observable<T> call(Observable<T> o) {
893 return o.compose(Transformers.
894 stateMachine()
895 .initialState(Optional.<T>absent())
896 .transition(new Transition<Optional<T>, T, T>() {
897
898 @Override
899 public Optional<T> call(Optional<T> state, T value,
900 Subscriber<T> subscriber) {
901 if (!state.isPresent()) {
902 if (isCandidateForFirst.call(value)) {
903 return Optional.of(value);
904 } else {
905 subscriber.onNext(value);
906 return Optional.absent();
907 }
908 } else {
909 if (remove.call(state.get(), value)) {
910
911 return Optional.absent();
912 } else {
913 subscriber.onNext(state.get());
914 if (isCandidateForFirst.call(value)) {
915 return Optional.of(value);
916 } else {
917 subscriber.onNext(value);
918 return Optional.absent();
919 }
920 }
921 }
922 }
923 }).completion(new Completion<Optional<T>, T>() {
924
925 @Override
926 public Boolean call(Optional<T> state, Subscriber<T> subscriber) {
927 if (state.isPresent())
928 subscriber.onNext(state.get());
929
930 return true;
931 }
932 }).build());
933 }
934 };
935 }
936
937
938
939
940
941
942
943
944
945
946
947
948 public static <T> Transformer<T, T> onBackpressureBufferRequestLimiting() {
949 return TransformerOnBackpressureBufferRequestLimiting.instance();
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 public static final <T> Transformer<T, List<T>> bufferUntil(
979 Func1<? super T, Boolean> predicate) {
980 return bufferUntil(predicate, 10);
981 }
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009 public static final <T> Transformer<T, List<T>> toListUntil(
1010 Func1<? super T, Boolean> predicate) {
1011 return bufferUntil(predicate);
1012 }
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042 public static final <T> Transformer<T, List<T>> bufferUntil(Func1<? super T, Boolean> predicate,
1043 int capacityHint) {
1044 return new OperatorBufferPredicateBoundary<T>(predicate, RxRingBuffer.SIZE, capacityHint,
1045 true);
1046 }
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076 public static final <T> Transformer<T, List<T>> toListUntil(Func1<? super T, Boolean> predicate,
1077 int capacityHint) {
1078 return bufferUntil(predicate, capacityHint);
1079 }
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108 public static final <T> Transformer<T, List<T>> bufferWhile(
1109 Func1<? super T, Boolean> predicate) {
1110 return bufferWhile(predicate, 10);
1111 }
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140 public static final <T> Transformer<T, List<T>> toListWhile(
1141 Func1<? super T, Boolean> predicate) {
1142 return bufferWhile(predicate);
1143 }
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173 public static final <T> Transformer<T, List<T>> bufferWhile(Func1<? super T, Boolean> predicate,
1174 int capacityHint) {
1175 return new OperatorBufferPredicateBoundary<T>(predicate, RxRingBuffer.SIZE, capacityHint,
1176 false);
1177 }
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207 public static final <T> Transformer<T, List<T>> toListWhile(Func1<? super T, Boolean> predicate,
1208 int capacityHint) {
1209 return bufferWhile(predicate, capacityHint);
1210 }
1211
1212 public static final <T> Transformer<T, T> delay(final Func1<? super T, Long> time,
1213 final Func0<Double> playRate, final long startTime, final Scheduler scheduler) {
1214 return new Transformer<T, T>() {
1215
1216 @Override
1217 public Observable<T> call(final Observable<T> o) {
1218 return Observable.defer(new Func0<Observable<T>>() {
1219 long startActual = scheduler.now();
1220
1221 @Override
1222 public Observable<T> call() {
1223 return o.concatMap(new Func1<T, Observable<T>>() {
1224
1225 @Override
1226 public Observable<T> call(T t) {
1227 return Observable.just(t)
1228 .delay(delay(startActual, startTime, time.call(t), playRate,
1229 scheduler.now()), TimeUnit.MILLISECONDS, scheduler);
1230 }
1231
1232 });
1233 }
1234 });
1235 }
1236 };
1237
1238 }
1239
1240 private static long delay(long startActual, long startTime, long emissionTimestamp,
1241 Func0<Double> playRate, long now) {
1242 long elapsedActual = now - startActual;
1243 return Math.max(0,
1244 Math.round((emissionTimestamp - startTime) / playRate.call() - elapsedActual));
1245 }
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264 public static final <T> Transformer<T, T> doOnEmpty(final Action0 onEmpty) {
1265 return new Transformer<T, T>() {
1266
1267 @Override
1268 public Observable<T> call(Observable<T> o) {
1269 return Observable.create(new OnSubscribeDoOnEmpty<T>(o, onEmpty));
1270 }
1271 };
1272 }
1273
1274 public static final <T> Transformer<T, T> onTerminateResume(
1275 final Func1<Throwable, Observable<T>> onError, final Observable<T> onCompleted) {
1276 return new TransformerOnTerminateResume<T>(onError, onCompleted);
1277 }
1278
1279 public static final <T> Transformer<T, T> repeatLast() {
1280 return new Transformer<T, T>() {
1281
1282 @Override
1283 public Observable<T> call(Observable<T> o) {
1284 return o.materialize().buffer(2, 1)
1285 .flatMap(new Func1<List<Notification<T>>, Observable<T>>() {
1286 @Override
1287 public Observable<T> call(List<Notification<T>> list) {
1288 Notification<T> a = list.get(0);
1289 if (list.size() == 2 && list.get(1).isOnCompleted()) {
1290 return Observable.just(a.getValue()).repeat();
1291 } else if (a.isOnError()) {
1292 return Observable.error(list.get(0).getThrowable());
1293 } else if (a.isOnCompleted()) {
1294 return Observable.empty();
1295 } else {
1296 return Observable.just(a.getValue());
1297 }
1298 }
1299 });
1300 }
1301 };
1302 }
1303
1304 public static <T> Transformer<T, T> mapLast(final Func1<? super T, ? extends T> function) {
1305
1306 return new Transformer<T, T>() {
1307
1308 @Override
1309 public Observable<T> call(Observable<T> source) {
1310 return Observable.create(new OnSubscribeMapLast<T>(source, function));
1311 }
1312 };
1313 }
1314 }