-
Notifications
You must be signed in to change notification settings - Fork 7.6k
/
Completable.java
2394 lines (2132 loc) · 88.3 KB
/
Completable.java
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
/**
* Copyright 2014 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package rx;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;
import rx.exceptions.*;
import rx.functions.*;
import rx.internal.observers.AssertableSubscriberObservable;
import rx.internal.operators.*;
import rx.internal.util.*;
import rx.observers.*;
import rx.plugins.RxJavaHooks;
import rx.schedulers.Schedulers;
import rx.subscriptions.*;
/**
* Represents a deferred computation without any value but only indication for completion or exception.
*
* The class follows a similar event pattern as Reactive-Streams: onSubscribe (onError|onComplete)?
*
* @since 1.3
*/
public class Completable {
/** The actual subscription action. */
private final OnSubscribe onSubscribe;
/**
* Callback used for building deferred computations that takes a CompletableSubscriber.
*/
public interface OnSubscribe extends Action1<rx.CompletableSubscriber> {
}
/**
* Convenience interface and callback used by the lift operator that given a child CompletableSubscriber,
* return a parent CompletableSubscriber that does any kind of lifecycle-related transformations.
*/
public interface Operator extends Func1<rx.CompletableSubscriber, rx.CompletableSubscriber> {
}
/**
* Convenience interface and callback used by the compose operator to turn a Completable into another
* Completable fluently.
*/
public interface Transformer extends Func1<Completable, Completable> {
}
/** Single instance of a complete Completable. */
static final Completable COMPLETE = new Completable(new OnSubscribe() {
@Override
public void call(rx.CompletableSubscriber s) {
s.onSubscribe(Subscriptions.unsubscribed());
s.onCompleted();
}
}, false); // hook is handled in complete()
/** Single instance of a never Completable. */
static final Completable NEVER = new Completable(new OnSubscribe() {
@Override
public void call(rx.CompletableSubscriber s) {
s.onSubscribe(Subscriptions.unsubscribed());
}
}, false); // hook is handled in never()
/**
* Returns a Completable which terminates as soon as one of the source Completables
* terminates (normally or with an error) and cancels all other Completables.
* @param sources the array of source Completables
* @return the new Completable instance
* @throws NullPointerException if sources is null
*/
public static Completable amb(final Completable... sources) {
requireNonNull(sources);
if (sources.length == 0) {
return complete();
}
if (sources.length == 1) {
return sources[0];
}
return create(new OnSubscribe() {
@Override
public void call(final rx.CompletableSubscriber s) {
final CompositeSubscription set = new CompositeSubscription();
s.onSubscribe(set);
final AtomicBoolean once = new AtomicBoolean();
rx.CompletableSubscriber inner = new rx.CompletableSubscriber() {
@Override
public void onCompleted() {
if (once.compareAndSet(false, true)) {
set.unsubscribe();
s.onCompleted();
}
}
@Override
public void onError(Throwable e) {
if (once.compareAndSet(false, true)) {
set.unsubscribe();
s.onError(e);
} else {
RxJavaHooks.onError(e);
}
}
@Override
public void onSubscribe(Subscription d) {
set.add(d);
}
};
for (Completable c : sources) {
if (set.isUnsubscribed()) {
return;
}
if (c == null) {
NullPointerException npe = new NullPointerException("One of the sources is null");
if (once.compareAndSet(false, true)) {
set.unsubscribe();
s.onError(npe);
} else {
RxJavaHooks.onError(npe);
}
return;
}
if (once.get() || set.isUnsubscribed()) {
return;
}
// no need to have separate subscribers because inner is stateless
c.unsafeSubscribe(inner);
}
}
});
}
/**
* Returns a Completable which terminates as soon as one of the source Completables
* terminates (normally or with an error) and cancels all other Completables.
* @param sources the array of source Completables
* @return the new Completable instance
* @throws NullPointerException if sources is null
*/
public static Completable amb(final Iterable<? extends Completable> sources) {
requireNonNull(sources);
return create(new OnSubscribe() {
@Override
public void call(final rx.CompletableSubscriber s) {
final CompositeSubscription set = new CompositeSubscription();
s.onSubscribe(set);
Iterator<? extends Completable> it;
try {
it = sources.iterator();
} catch (Throwable e) {
s.onError(e);
return;
}
if (it == null) {
s.onError(new NullPointerException("The iterator returned is null"));
return;
}
boolean empty = true;
final AtomicBoolean once = new AtomicBoolean();
rx.CompletableSubscriber inner = new rx.CompletableSubscriber() {
@Override
public void onCompleted() {
if (once.compareAndSet(false, true)) {
set.unsubscribe();
s.onCompleted();
}
}
@Override
public void onError(Throwable e) {
if (once.compareAndSet(false, true)) {
set.unsubscribe();
s.onError(e);
} else {
RxJavaHooks.onError(e);
}
}
@Override
public void onSubscribe(Subscription d) {
set.add(d);
}
};
for (;;) {
if (once.get() || set.isUnsubscribed()) {
return;
}
boolean b;
try {
b = it.hasNext();
} catch (Throwable e) {
if (once.compareAndSet(false, true)) {
set.unsubscribe();
s.onError(e);
} else {
RxJavaHooks.onError(e);
}
return;
}
if (!b) {
if (empty) {
s.onCompleted();
}
break;
}
empty = false;
if (once.get() || set.isUnsubscribed()) {
return;
}
Completable c;
try {
c = it.next();
} catch (Throwable e) {
if (once.compareAndSet(false, true)) {
set.unsubscribe();
s.onError(e);
} else {
RxJavaHooks.onError(e);
}
return;
}
if (c == null) {
NullPointerException npe = new NullPointerException("One of the sources is null");
if (once.compareAndSet(false, true)) {
set.unsubscribe();
s.onError(npe);
} else {
RxJavaHooks.onError(npe);
}
return;
}
if (once.get() || set.isUnsubscribed()) {
return;
}
// no need to have separate subscribers because inner is stateless
c.unsafeSubscribe(inner);
}
}
});
}
/**
* Returns a Completable instance that completes immediately when subscribed to.
* @return a Completable instance that completes immediately
*/
public static Completable complete() {
OnSubscribe cos = RxJavaHooks.onCreate(COMPLETE.onSubscribe);
if (cos == COMPLETE.onSubscribe) {
return COMPLETE;
}
return new Completable(cos, false);
}
/**
* Returns a Completable which completes only when all sources complete, one after another.
* @param sources the sources to concatenate
* @return the Completable instance which completes only when all sources complete
* @throws NullPointerException if sources is null
*/
public static Completable concat(Completable... sources) {
requireNonNull(sources);
if (sources.length == 0) {
return complete();
} else
if (sources.length == 1) {
return sources[0];
}
return create(new CompletableOnSubscribeConcatArray(sources));
}
/**
* Returns a Completable which completes only when all sources complete, one after another.
* @param sources the sources to concatenate
* @return the Completable instance which completes only when all sources complete
* @throws NullPointerException if sources is null
*/
public static Completable concat(Iterable<? extends Completable> sources) {
requireNonNull(sources);
return create(new CompletableOnSubscribeConcatIterable(sources));
}
/**
* Returns a Completable which completes only when all sources complete, one after another.
* @param sources the sources to concatenate
* @return the Completable instance which completes only when all sources complete
* @throws NullPointerException if sources is null
*/
public static Completable concat(Observable<? extends Completable> sources) {
return concat(sources, 2);
}
/**
* Returns a Completable which completes only when all sources complete, one after another.
* @param sources the sources to concatenate
* @param prefetch the number of sources to prefetch from the sources
* @return the Completable instance which completes only when all sources complete
* @throws NullPointerException if sources is null
*/
public static Completable concat(Observable<? extends Completable> sources, int prefetch) {
requireNonNull(sources);
if (prefetch < 1) {
throw new IllegalArgumentException("prefetch > 0 required but it was " + prefetch);
}
return create(new CompletableOnSubscribeConcat(sources, prefetch));
}
/**
* Constructs a Completable instance by wrapping the given onSubscribe callback.
* @param onSubscribe the callback which will receive the CompletableSubscriber instances
* when the Completable is subscribed to.
* @return the created Completable instance
* @throws NullPointerException if onSubscribe is null
*/
public static Completable create(OnSubscribe onSubscribe) {
requireNonNull(onSubscribe);
try {
return new Completable(onSubscribe);
} catch (NullPointerException ex) { // NOPMD
throw ex;
} catch (Throwable ex) {
RxJavaHooks.onError(ex);
throw toNpe(ex);
}
}
/**
* Defers the subscription to a Completable instance returned by a supplier.
* @param completableFunc0 the supplier that returns the Completable that will be subscribed to.
* @return the Completable instance
*/
public static Completable defer(final Func0<? extends Completable> completableFunc0) {
requireNonNull(completableFunc0);
return create(new OnSubscribe() {
@Override
public void call(rx.CompletableSubscriber s) {
Completable c;
try {
c = completableFunc0.call();
} catch (Throwable e) {
s.onSubscribe(Subscriptions.unsubscribed());
s.onError(e);
return;
}
if (c == null) {
s.onSubscribe(Subscriptions.unsubscribed());
s.onError(new NullPointerException("The completable returned is null"));
return;
}
c.unsafeSubscribe(s);
}
});
}
/**
* Creates a Completable which calls the given error supplier for each subscriber
* and emits its returned Throwable.
* <p>
* If the errorFunc0 returns null, the child CompletableSubscribers will receive a
* NullPointerException.
* @param errorFunc0 the error supplier, not null
* @return the new Completable instance
* @throws NullPointerException if errorFunc0 is null
*/
public static Completable error(final Func0<? extends Throwable> errorFunc0) {
requireNonNull(errorFunc0);
return create(new OnSubscribe() {
@Override
public void call(rx.CompletableSubscriber s) {
s.onSubscribe(Subscriptions.unsubscribed());
Throwable error;
try {
error = errorFunc0.call();
} catch (Throwable e) {
error = e;
}
if (error == null) {
error = new NullPointerException("The error supplied is null");
}
s.onError(error);
}
});
}
/**
* Creates a Completable instance that emits the given Throwable exception to subscribers.
* @param error the Throwable instance to emit, not null
* @return the new Completable instance
* @throws NullPointerException if error is null
*/
public static Completable error(final Throwable error) {
requireNonNull(error);
return create(new OnSubscribe() {
@Override
public void call(rx.CompletableSubscriber s) {
s.onSubscribe(Subscriptions.unsubscribed());
s.onError(error);
}
});
}
/**
* Returns a Completable instance that runs the given Action0 for each subscriber and
* emits either an unchecked exception or simply completes.
* @param action the Action0 to run for each subscriber
* @return the new Completable instance
* @throws NullPointerException if run is null
*/
public static Completable fromAction(final Action0 action) {
requireNonNull(action);
return create(new OnSubscribe() {
@Override
public void call(rx.CompletableSubscriber s) {
BooleanSubscription bs = new BooleanSubscription();
s.onSubscribe(bs);
try {
action.call();
} catch (Throwable e) {
if (!bs.isUnsubscribed()) {
s.onError(e);
}
return;
}
if (!bs.isUnsubscribed()) {
s.onCompleted();
}
}
});
}
/**
* Returns a Completable which when subscribed, executes the callable function, ignores its
* normal result and emits onError or onCompleted only.
* @param callable the callable instance to execute for each subscriber
* @return the new Completable instance
*/
public static Completable fromCallable(final Callable<?> callable) {
requireNonNull(callable);
return create(new OnSubscribe() {
@Override
public void call(rx.CompletableSubscriber s) {
BooleanSubscription bs = new BooleanSubscription();
s.onSubscribe(bs);
try {
callable.call();
} catch (Throwable e) {
if (!bs.isUnsubscribed()) {
s.onError(e);
}
return;
}
if (!bs.isUnsubscribed()) {
s.onCompleted();
}
}
});
}
/**
* Provides an API (in a cold Completable) that bridges the Completable-reactive world
* with the callback-based world.
* <p>The {@link CompletableEmitter} allows registering a callback for
* cancellation/unsubscription of a resource.
* <p>
* Example:
* <pre><code>
* Completable.fromEmitter(emitter -> {
* Callback listener = new Callback() {
* @Override
* public void onEvent(Event e) {
* emitter.onCompleted();
* }
*
* @Override
* public void onFailure(Exception e) {
* emitter.onError(e);
* }
* };
*
* AutoCloseable c = api.someMethod(listener);
*
* emitter.setCancellation(c::close);
*
* });
* </code></pre>
* <p>All of the CompletableEmitter's methods are thread-safe and ensure the
* Completable's protocol are held.
* @param producer the callback invoked for each incoming CompletableSubscriber
* @return the new Completable instance
* @since 1.3
*/
public static Completable fromEmitter(Action1<CompletableEmitter> producer) {
return create(new CompletableFromEmitter(producer));
}
/**
* Returns a Completable instance that reacts to the termination of the given Future in a blocking fashion.
* <p>
* Note that cancellation from any of the subscribers to this Completable will cancel the future.
* @param future the future to react to
* @return the new Completable instance
*/
public static Completable fromFuture(Future<?> future) {
requireNonNull(future);
return fromObservable(Observable.from(future));
}
/**
* Returns a Completable instance that subscribes to the given flowable, ignores all values and
* emits only the terminal event.
* @param flowable the Flowable instance to subscribe to, not null
* @return the new Completable instance
* @throws NullPointerException if flowable is null
*/
public static Completable fromObservable(final Observable<?> flowable) {
requireNonNull(flowable);
return create(new OnSubscribe() {
@Override
public void call(final rx.CompletableSubscriber cs) {
Subscriber<Object> subscriber = new Subscriber<Object>() {
@Override
public void onCompleted() {
cs.onCompleted();
}
@Override
public void onError(Throwable t) {
cs.onError(t);
}
@Override
public void onNext(Object t) {
// ignored
}
};
cs.onSubscribe(subscriber);
flowable.unsafeSubscribe(subscriber);
}
});
}
/**
* Returns a Completable instance that when subscribed to, subscribes to the Single instance and
* emits a completion event if the single emits onSuccess or forwards any onError events.
* @param single the Single instance to subscribe to, not null
* @return the new Completable instance
* @throws NullPointerException if single is null
*/
public static Completable fromSingle(final Single<?> single) {
requireNonNull(single);
return create(new OnSubscribe() {
@Override
public void call(final rx.CompletableSubscriber s) {
SingleSubscriber<Object> te = new SingleSubscriber<Object>() {
@Override
public void onError(Throwable e) {
s.onError(e);
}
@Override
public void onSuccess(Object value) {
s.onCompleted();
}
};
s.onSubscribe(te);
single.subscribe(te);
}
});
}
/**
* Returns a Completable instance that subscribes to all sources at once and
* completes only when all source Completables complete or one of them emits an error.
* @param sources the iterable sequence of sources.
* @return the new Completable instance
* @throws NullPointerException if sources is null
*/
public static Completable merge(Completable... sources) {
requireNonNull(sources);
if (sources.length == 0) {
return complete();
} else
if (sources.length == 1) {
return sources[0];
}
return create(new CompletableOnSubscribeMergeArray(sources));
}
/**
* Returns a Completable instance that subscribes to all sources at once and
* completes only when all source Completables complete or one of them emits an error.
* @param sources the iterable sequence of sources.
* @return the new Completable instance
* @throws NullPointerException if sources is null
*/
public static Completable merge(Iterable<? extends Completable> sources) {
requireNonNull(sources);
return create(new CompletableOnSubscribeMergeIterable(sources));
}
/**
* Returns a Completable instance that subscribes to all sources at once and
* completes only when all source Completables complete or one of them emits an error.
* @param sources the iterable sequence of sources.
* @return the new Completable instance
* @throws NullPointerException if sources is null
*/
public static Completable merge(Observable<? extends Completable> sources) {
return merge0(sources, Integer.MAX_VALUE, false);
}
/**
* Returns a Completable instance that keeps subscriptions to a limited number of sources at once and
* completes only when all source Completables complete or one of them emits an error.
* @param sources the iterable sequence of sources.
* @param maxConcurrency the maximum number of concurrent subscriptions
* @return the new Completable instance
* @throws NullPointerException if sources is null
* @throws IllegalArgumentException if maxConcurrency is less than 1
*/
public static Completable merge(Observable<? extends Completable> sources, int maxConcurrency) {
return merge0(sources, maxConcurrency, false);
}
/**
* Returns a Completable instance that keeps subscriptions to a limited number of sources at once and
* completes only when all source Completables terminate in one way or another, combining any exceptions
* thrown by either the sources Observable or the inner Completable instances.
* @param sources the iterable sequence of sources.
* @param maxConcurrency the maximum number of concurrent subscriptions
* @param delayErrors delay all errors from the main source and from the inner Completables?
* @return the new Completable instance
* @throws NullPointerException if sources is null
* @throws IllegalArgumentException if maxConcurrency is less than 1
*/
protected static Completable merge0(Observable<? extends Completable> sources, int maxConcurrency, boolean delayErrors) {
requireNonNull(sources);
if (maxConcurrency < 1) {
throw new IllegalArgumentException("maxConcurrency > 0 required but it was " + maxConcurrency);
}
return create(new CompletableOnSubscribeMerge(sources, maxConcurrency, delayErrors));
}
/**
* Returns a Completable that subscribes to all Completables in the source array and delays
* any error emitted by either the sources observable or any of the inner Completables until all of
* them terminate in a way or another.
* @param sources the array of Completables
* @return the new Completable instance
* @throws NullPointerException if sources is null
*/
public static Completable mergeDelayError(Completable... sources) {
requireNonNull(sources);
return create(new CompletableOnSubscribeMergeDelayErrorArray(sources));
}
/**
* Returns a Completable that subscribes to all Completables in the source sequence and delays
* any error emitted by either the sources observable or any of the inner Completables until all of
* them terminate in a way or another.
* @param sources the sequence of Completables
* @return the new Completable instance
* @throws NullPointerException if sources is null
*/
public static Completable mergeDelayError(Iterable<? extends Completable> sources) {
requireNonNull(sources);
return create(new CompletableOnSubscribeMergeDelayErrorIterable(sources));
}
/**
* Returns a Completable that subscribes to all Completables in the source sequence and delays
* any error emitted by either the sources observable or any of the inner Completables until all of
* them terminate in a way or another.
* @param sources the sequence of Completables
* @return the new Completable instance
* @throws NullPointerException if sources is null
*/
public static Completable mergeDelayError(Observable<? extends Completable> sources) {
return merge0(sources, Integer.MAX_VALUE, true);
}
/**
* Returns a Completable that subscribes to a limited number of inner Completables at once in
* the source sequence and delays any error emitted by either the sources
* observable or any of the inner Completables until all of
* them terminate in a way or another.
* @param sources the sequence of Completables
* @param maxConcurrency the maximum number of simultaneous subscriptions to the source Completables.
* @return the new Completable instance
* @throws NullPointerException if sources is null
*/
public static Completable mergeDelayError(Observable<? extends Completable> sources, int maxConcurrency) {
return merge0(sources, maxConcurrency, true);
}
/**
* Returns a Completable that never calls onError or onComplete.
* @return the singleton instance that never calls onError or onComplete
*/
public static Completable never() {
OnSubscribe cos = RxJavaHooks.onCreate(NEVER.onSubscribe);
if (cos == NEVER.onSubscribe) {
return NEVER;
}
return new Completable(cos, false);
}
/**
* Java 7 backport: throws a NullPointerException if o is null.
* @param o the object to check
* @return the o value
* @throws NullPointerException if o is null
*/
static <T> T requireNonNull(T o) {
if (o == null) {
throw new NullPointerException();
}
return o;
}
/**
* Returns a Completable instance that fires its onComplete event after the given delay elapsed.
* @param delay the delay time
* @param unit the delay unit
* @return the new Completable instance
*/
public static Completable timer(long delay, TimeUnit unit) {
return timer(delay, unit, Schedulers.computation());
}
/**
* Returns a Completable instance that fires its onCompleted event after the given delay elapsed
* by using the supplied scheduler.
* @param delay the delay time
* @param unit the delay unit
* @param scheduler the scheduler to use to emit the onCompleted event
* @return the new Completable instance
*/
public static Completable timer(final long delay, final TimeUnit unit, final Scheduler scheduler) {
requireNonNull(unit);
requireNonNull(scheduler);
return create(new OnSubscribe() {
@Override
public void call(final rx.CompletableSubscriber s) {
MultipleAssignmentSubscription mad = new MultipleAssignmentSubscription();
s.onSubscribe(mad);
if (!mad.isUnsubscribed()) {
final Scheduler.Worker w = scheduler.createWorker();
mad.set(w);
w.schedule(new Action0() {
@Override
public void call() {
try {
s.onCompleted();
} finally {
w.unsubscribe();
}
}
}, delay, unit);
}
}
});
}
/**
* Creates a NullPointerException instance and sets the given Throwable as its initial cause.
* @param ex the Throwable instance to use as cause, not null (not verified)
* @return the created NullPointerException
*/
static NullPointerException toNpe(Throwable ex) {
NullPointerException npe = new NullPointerException("Actually not, but can't pass out an exception otherwise...");
npe.initCause(ex);
return npe;
}
/**
* Returns a Completable instance which manages a resource along
* with a custom Completable instance while the subscription is active.
* <p>
* This overload performs an eager unsubscription before the terminal event is emitted.
*
* @param <R> the resource type
* @param resourceFunc0 the supplier that returns a resource to be managed.
* @param completableFunc1 the function that given a resource returns a Completable instance that will be subscribed to
* @param disposer the consumer that disposes the resource created by the resource supplier
* @return the new Completable instance
*/
public static <R> Completable using(Func0<R> resourceFunc0,
Func1<? super R, ? extends Completable> completableFunc1,
Action1<? super R> disposer) {
return using(resourceFunc0, completableFunc1, disposer, true);
}
/**
* Returns a Completable instance which manages a resource along
* with a custom Completable instance while the subscription is active and performs eager or lazy
* resource disposition.
* <p>
* If this overload performs a lazy unsubscription after the terminal event is emitted.
* Exceptions thrown at this time will be delivered to RxJavaPlugins only.
*
* @param <R> the resource type
* @param resourceFunc0 the supplier that returns a resource to be managed
* @param completableFunc1 the function that given a resource returns a non-null
* Completable instance that will be subscribed to
* @param disposer the consumer that disposes the resource created by the resource supplier
* @param eager if true, the resource is disposed before the terminal event is emitted, if false, the
* resource is disposed after the terminal event has been emitted
* @return the new Completable instance
*/
public static <R> Completable using(final Func0<R> resourceFunc0,
final Func1<? super R, ? extends Completable> completableFunc1,
final Action1<? super R> disposer,
final boolean eager) {
requireNonNull(resourceFunc0);
requireNonNull(completableFunc1);
requireNonNull(disposer);
return create(new OnSubscribe() {
@Override
public void call(final rx.CompletableSubscriber s) {
final R resource; // NOPMD
try {
resource = resourceFunc0.call();
} catch (Throwable e) {
s.onSubscribe(Subscriptions.unsubscribed());
s.onError(e);
return;
}
Completable cs;
try {
cs = completableFunc1.call(resource);
} catch (Throwable e) {
try {
disposer.call(resource);
} catch (Throwable ex) {
Exceptions.throwIfFatal(e);
Exceptions.throwIfFatal(ex);
s.onSubscribe(Subscriptions.unsubscribed());
s.onError(new CompositeException(Arrays.asList(e, ex)));
return;
}
Exceptions.throwIfFatal(e);
s.onSubscribe(Subscriptions.unsubscribed());
s.onError(e);
return;
}
if (cs == null) {
try {
disposer.call(resource);
} catch (Throwable ex) {
Exceptions.throwIfFatal(ex);
s.onSubscribe(Subscriptions.unsubscribed());
s.onError(new CompositeException(Arrays.asList(new NullPointerException("The completable supplied is null"), ex)));
return;
}
s.onSubscribe(Subscriptions.unsubscribed());
s.onError(new NullPointerException("The completable supplied is null"));
return;
}
final AtomicBoolean once = new AtomicBoolean();
cs.unsafeSubscribe(new rx.CompletableSubscriber() {
Subscription d;
void dispose() {
d.unsubscribe();
if (once.compareAndSet(false, true)) {
try {
disposer.call(resource);
} catch (Throwable ex) {
RxJavaHooks.onError(ex);
}
}
}
@Override
public void onCompleted() {
if (eager) {
if (once.compareAndSet(false, true)) {
try {
disposer.call(resource);
} catch (Throwable ex) {
s.onError(ex);
return;
}
}
}
s.onCompleted();
if (!eager) {
dispose();
}
}
@Override
public void onError(Throwable e) {
if (eager) {
if (once.compareAndSet(false, true)) {
try {
disposer.call(resource);
} catch (Throwable ex) {
e = new CompositeException(Arrays.asList(e, ex));
}
}
}
s.onError(e);
if (!eager) {
dispose();
}
}
@Override
public void onSubscribe(Subscription d) {
this.d = d;
s.onSubscribe(Subscriptions.create(new Action0() {
@Override
public void call() {
dispose();
}
}));
}
});
}
});
}
/**
* Constructs a Completable instance with the given onSubscribe callback.
* @param onSubscribe the callback that will receive CompletableSubscribers when they subscribe,
* not null (not verified)
*/
protected Completable(OnSubscribe onSubscribe) {
this.onSubscribe = RxJavaHooks.onCreate(onSubscribe);
}