-
Notifications
You must be signed in to change notification settings - Fork 180
/
Completable.java
1645 lines (1554 loc) · 79.8 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 © 2018-2019 Apple Inc. and the ServiceTalk project authors
*
* 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 io.servicetalk.concurrent.api;
import io.servicetalk.concurrent.Cancellable;
import io.servicetalk.concurrent.CompletableSource;
import io.servicetalk.concurrent.CompletableSource.Subscriber;
import io.servicetalk.concurrent.api.SourceToFuture.CompletableToFuture;
import io.servicetalk.concurrent.internal.SignalOffloader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.time.Duration;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.function.BiFunction;
import java.util.function.BiPredicate;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.IntFunction;
import java.util.function.IntPredicate;
import java.util.function.Supplier;
import static io.servicetalk.concurrent.Cancellable.IGNORE_CANCEL;
import static io.servicetalk.concurrent.api.CompletableDoOnUtils.doOnCompleteSupplier;
import static io.servicetalk.concurrent.api.CompletableDoOnUtils.doOnErrorSupplier;
import static io.servicetalk.concurrent.api.CompletableDoOnUtils.doOnSubscribeSupplier;
import static io.servicetalk.concurrent.api.Executors.immediate;
import static io.servicetalk.concurrent.api.Publisher.from;
import static io.servicetalk.concurrent.api.Publisher.fromIterable;
import static io.servicetalk.concurrent.internal.SignalOffloaders.newOffloaderFor;
import static java.util.Objects.requireNonNull;
import static java.util.function.Function.identity;
/**
* An asynchronous computation that does not emit any data. It just completes or emits an error.
*
* <h2>How to subscribe?</h2>
*
* This class does not provide a way to subscribe using a {@link CompletableSource.Subscriber} as such calls are
* ambiguous about the intent whether the subscribe is part of the same source (a.k.a an operator) or it is a terminal
* subscribe. If it is required to subscribe to a source, then a {@link SourceAdapters source adapter} can be used to
* convert to a {@link CompletableSource}.
*/
public abstract class Completable {
private static final Logger LOGGER = LoggerFactory.getLogger(Completable.class);
private final Executor executor;
private final boolean shareContextOnSubscribe;
static {
AsyncContext.autoEnable();
}
/**
* New instance.
*/
protected Completable() {
this(immediate());
}
/**
* New instance.
*
* @param executor {@link Executor} to use for this {@link Completable}.
*/
Completable(final Executor executor) {
this(executor, false);
}
/**
* New instance.
*
* @param executor {@link Executor} to use for this {@link Completable}.
* @param shareContextOnSubscribe When subscribed, a copy of the {@link AsyncContextMap} will not be made. This will
* result in sharing {@link AsyncContext} between sources.
*/
Completable(Executor executor, boolean shareContextOnSubscribe) {
this.executor = requireNonNull(executor);
this.shareContextOnSubscribe = shareContextOnSubscribe;
}
//
// Operators Begin
//
/**
* Recover from any error emitted by this {@link Completable} by using another {@link Completable} provided by the
* passed {@code nextFactory}.
* <p>
* This method provides similar capabilities to a try/catch block in sequential programming:
* <pre>{@code
* try {
* resultOfThisCompletable();
* } catch (Throwable cause) {
* // Note that nextFactory returning a error Completable is like re-throwing (nextFactory shouldn't throw).
* nextFactory.apply(cause);
* }
* }</pre>
*
* @param nextFactory Returns the next {@link Completable}, if this {@link Completable} emits an error.
* @return A {@link Completable} that recovers from an error from this {@code Completable} by using another
* {@link Completable} provided by the passed {@code nextFactory}.
*/
public final Completable onErrorResume(Function<Throwable, ? extends Completable> nextFactory) {
return new ResumeCompletable(this, nextFactory, executor);
}
/**
* Invokes the {@code onComplete} {@link Runnable} argument when {@link Subscriber#onComplete()} is called for
* {@link Subscriber}s of the returned {@link Completable}.
* <p>
* The order in which {@code onComplete} will be invoked relative to {@link Subscriber#onComplete()} is
* undefined. If you need strict ordering see {@link #beforeOnComplete(Runnable)} and
* {@link #afterOnComplete(Runnable)}.
* <p>
* From a sequential programming point of view this method is roughly equivalent to the following:
* <pre>{@code
* // NOTE: The order of operations here is not guaranteed by this method!
* nextOperation(result);
* onComplete.run();
* }</pre>
*
* @param onComplete Invoked when {@link Subscriber#onComplete()} is called for {@link Subscriber}s of the returned
* {@link Completable}. <strong>MUST NOT</strong> throw.
* @return The new {@link Completable}.
* @see #beforeOnComplete(Runnable)
* @see #afterOnComplete(Runnable)
*/
public final Completable whenOnComplete(Runnable onComplete) {
return afterOnComplete(onComplete);
}
/**
* Invokes the {@code onError} {@link Consumer} argument when {@link Subscriber#onError(Throwable)} is called for
* {@link Subscriber}s of the returned {@link Completable}.
* <p>
* The order in which {@code onError} will be invoked relative to {@link Subscriber#onError(Throwable)} is
* undefined. If you need strict ordering see {@link #beforeOnError(Consumer)} and
* {@link #afterOnError(Consumer)}.
* <p>
* From a sequential programming point of view this method is roughly equivalent to the following:
* <pre>{@code
* try {
* resultOfThisCompletable();
* } catch (Throwable cause) {
* // NOTE: The order of operations here is not guaranteed by this method!
* nextOperation(cause);
* onError.accept(cause);
* }
* }</pre>
*
* @param onError Invoked when {@link Subscriber#onError(Throwable)} is called for {@link Subscriber}s of the
* returned {@link Completable}. <strong>MUST NOT</strong> throw.
* @return The new {@link Completable}.
* @see #beforeOnError(Consumer)
* @see #afterOnError(Consumer)
*/
public final Completable whenOnError(Consumer<Throwable> onError) {
return afterOnError(onError);
}
/**
* Invokes the {@code whenFinally} {@link Runnable} argument exactly once, when any of the following terminal
* methods are called:
* <ul>
* <li>{@link Subscriber#onComplete()}</li>
* <li>{@link Subscriber#onError(Throwable)}</li>
* <li>{@link Cancellable#cancel()}</li>
* </ul>
* for Subscriptions/{@link Subscriber}s of the returned {@link Completable}.
* <p>
* The order in which {@code whenFinally} will be invoked relative to the above methods is undefined. If you need
* strict ordering see {@link #beforeFinally(Runnable)} and {@link #afterFinally(Runnable)}.
* <p>
* From a sequential programming point of view this method is roughly equivalent to the following:
* <pre>{@code
* try {
* resultOfThisCompletable();
* } finally {
* // NOTE: The order of operations here is not guaranteed by this method!
* nextOperation(); // Maybe notifying of cancellation, or termination
* whenFinally.run();
* }
* }</pre>
*
* @param doFinally Invoked exactly once, when any of the following terminal methods are called:
* <ul>
* <li>{@link Subscriber#onComplete()}</li>
* <li>{@link Subscriber#onError(Throwable)}</li>
* <li>{@link Cancellable#cancel()}</li>
* </ul>
* for Subscriptions/{@link Subscriber}s of the returned {@link Completable} <strong>MUST NOT</strong> throw.
* @return The new {@link Completable}.
* @see #afterFinally(Runnable)
* @see #beforeFinally(Runnable)
*/
public final Completable whenFinally(Runnable doFinally) {
return afterFinally(doFinally);
}
/**
* Invokes the {@code onCancel} {@link Runnable} argument when {@link Cancellable#cancel()} is called for
* Subscriptions of the returned {@link Completable}.
* <p>
* The order in which {@code whenFinally} will be invoked relative to {@link Cancellable#cancel()} is undefined. If
* you need strict ordering see {@link #beforeCancel(Runnable)} and {@link #afterCancel(Runnable)}.
* @param onCancel Invoked when {@link Cancellable#cancel()} is called for Subscriptions of the
* returned {@link Completable}. <strong>MUST NOT</strong> throw.
* @return The new {@link Completable}.
* @see #beforeCancel(Runnable)
* @see #afterCancel(Runnable)
*/
public final Completable whenCancel(Runnable onCancel) {
return afterCancel(onCancel);
}
/**
* Creates a new {@link Completable} that will mimic the signals of this {@link Completable} but will terminate
* with a {@link TimeoutException} if time {@code duration} elapses between subscribe and termination.
* The timer starts when the returned {@link Completable} is subscribed.
* <p>
* In the event of timeout any {@link Cancellable} from {@link Subscriber#onSubscribe(Cancellable)} will be
* {@link Cancellable#cancel() cancelled} and the associated {@link Subscriber} will be
* {@link Subscriber#onError(Throwable) terminated}.
* @param duration The time duration which is allowed to elapse before {@link Subscriber#onComplete()}.
* @param unit The units for {@code duration}.
* @return a new {@link Completable} that will mimic the signals of this {@link Completable} but will terminate with
* a {@link TimeoutException} if time {@code duration} elapses before {@link Subscriber#onComplete()}.
* @see <a href="http://reactivex.io/documentation/operators/timeout.html">ReactiveX timeout operator.</a>
*/
public final Completable idleTimeout(long duration, TimeUnit unit) {
return idleTimeout(duration, unit, executor);
}
/**
* Creates a new {@link Completable} that will mimic the signals of this {@link Completable} but will terminate
* with a {@link TimeoutException} if time {@code duration} elapses between subscribe and termination.
* The timer starts when the returned {@link Completable} is subscribed.
* <p>
* In the event of timeout any {@link Cancellable} from {@link Subscriber#onSubscribe(Cancellable)} will be
* {@link Cancellable#cancel() cancelled} and the associated {@link Subscriber} will be
* {@link Subscriber#onError(Throwable) terminated}.
* @param duration The time duration which is allowed to elapse before {@link Subscriber#onComplete()}.
* @param unit The units for {@code duration}.
* @param timeoutExecutor The {@link Executor} to use for managing the timer notifications.
* @return a new {@link Completable} that will mimic the signals of this {@link Completable} but will terminate with
* a {@link TimeoutException} if time {@code duration} elapses before {@link Subscriber#onComplete()}.
* @see <a href="http://reactivex.io/documentation/operators/timeout.html">ReactiveX timeout operator.</a>
*/
public final Completable idleTimeout(long duration, TimeUnit unit, Executor timeoutExecutor) {
return new TimeoutCompletable(this, duration, unit, timeoutExecutor);
}
/**
* Creates a new {@link Completable} that will mimic the signals of this {@link Completable} but will terminate
* with a {@link TimeoutException} if time {@code duration} elapses between subscribe and termination.
* The timer starts when the returned {@link Completable} is subscribed.
* <p>
* In the event of timeout any {@link Cancellable} from {@link Subscriber#onSubscribe(Cancellable)} will be
* {@link Cancellable#cancel() cancelled} and the associated {@link Subscriber} will be
* {@link Subscriber#onError(Throwable) terminated}.
* @param duration The time duration which is allowed to elapse before {@link Subscriber#onComplete()}.
* @return a new {@link Completable} that will mimic the signals of this {@link Completable} but will terminate with
* a {@link TimeoutException} if time {@code duration} elapses before {@link Subscriber#onComplete()}.
* @see <a href="http://reactivex.io/documentation/operators/timeout.html">ReactiveX timeout operator.</a>
*/
public final Completable idleTimeout(Duration duration) {
return idleTimeout(duration, executor);
}
/**
* Creates a new {@link Completable} that will mimic the signals of this {@link Completable} but will terminate
* with a {@link TimeoutException} if time {@code duration} elapses between subscribe and termination.
* The timer starts when the returned {@link Completable} is subscribed.
* <p>
* In the event of timeout any {@link Cancellable} from {@link Subscriber#onSubscribe(Cancellable)} will be
* {@link Cancellable#cancel() cancelled} and the associated {@link Subscriber} will be
* {@link Subscriber#onError(Throwable) terminated}.
* @param duration The time duration which is allowed to elapse before {@link Subscriber#onComplete()}.
* @param timeoutExecutor The {@link Executor} to use for managing the timer notifications.
* @return a new {@link Completable} that will mimic the signals of this {@link Completable} but will terminate with
* a {@link TimeoutException} if time {@code duration} elapses before {@link Subscriber#onComplete()}.
* @see <a href="http://reactivex.io/documentation/operators/timeout.html">ReactiveX timeout operator.</a>
*/
public final Completable idleTimeout(Duration duration, Executor timeoutExecutor) {
return new TimeoutCompletable(this, duration, timeoutExecutor);
}
/**
* Once this {@link Completable} is terminated successfully, subscribe to {@code next} {@link Completable}
* and propagate its terminal signal to the returned {@link Completable}. Any error from this {@link Completable}
* or {@code next} {@link Completable} are propagated to the returned {@link Completable}.
* <p>
* This method provides a means to sequence the execution of two asynchronous sources and in sequential programming
* is similar to:
* <pre>{@code
* resultOfThisCompletable();
* nextCompletable();
* }</pre>
*
* @param next {@link Completable} to subscribe after this {@link Completable} terminates successfully.
* @return A {@link Completable} that emits the terminal signal of {@code next} {@link Completable}, after this
* {@link Completable} has terminated successfully.
*/
public final Completable concat(Completable next) {
return new CompletableConcatWithCompletable(this, next, executor);
}
/**
* Once this {@link Completable} is terminated successfully, subscribe to {@code next} {@link Single}
* and propagate the result to the returned {@link Single}. Any error from this {@link Completable} or {@code next}
* {@link Single} are propagated to the returned {@link Single}.
* <p>
* This method provides a means to sequence the execution of two asynchronous sources and in sequential programming
* is similar to:
* <pre>{@code
* resultOfThisCompletable();
* T result = resultOfNextSingle();
* return result;
* }</pre>
*
* @param next {@link Single} to subscribe after this {@link Completable} terminates successfully.
* @param <T> Type of result of the returned {@link Single}.
* @return A {@link Single} that emits the result of {@code next} {@link Single}, after this {@link Completable}
* has terminated successfully.
*/
public final <T> Single<T> concat(Single<? extends T> next) {
return new CompletableConcatWithSingle<>(this, next, executor);
}
/**
* Once this {@link Completable} is terminated successfully, subscribe to {@code next} {@link Publisher}
* and propagate all emissions to the returned {@link Publisher}. Any error from this {@link Completable} or
* {@code next} {@link Publisher} are propagated to the returned {@link Publisher}.
* <p>
* This method provides a means to sequence the execution of two asynchronous sources and in sequential programming
* is similar to:
* <pre>{@code
* List<T> results = new ...;
* resultOfThisCompletable();
* results.addAll(nextStream());
* return results;
* }</pre>
*
* @param next {@link Publisher} to subscribe after this {@link Completable} terminates successfully.
* @param <T> Type of objects emitted from the returned {@link Publisher}.
* @return A {@link Publisher} that emits all items emitted from {@code next} {@link Publisher}, after this
* {@link Completable} has terminated successfully.
*/
public final <T> Publisher<T> concat(Publisher<? extends T> next) {
return new CompletableConcatWithPublisher<>(this, next, executor);
}
/**
* Merges this {@link Completable} with the {@code other} {@link Completable}s so that the resulting
* {@link Completable} terminates successfully when all of these complete or terminates with an error when any one
* terminates with an error.
* <p>
* This method provides a means to merge multiple asynchronous sources, fails-fast in the presence of any errors,
* and in sequential programming is similar to:
* <pre>{@code
* ExecutorService e = ...;
* List<Future<Void>> futures = ...;
* futures.add(e.submit(() -> resultOfThisCompletable()));
* for (Completable c : other) {
* futures.add(e.submit(() -> resultOfCompletable(c));
* }
* // This is an approximation, this operator does not provide any ordering guarantees for the results.
* for (Future<Void> future : futures) {
* future.get(); // Throws if the processing for this item failed.
* }
* }</pre>
*
* @param other {@link Completable}s to merge.
* @return {@link Completable} that terminates successfully when this and all {@code other} {@link Completable}s
* complete or terminates with an error when any one terminates with an error.
*/
public final Completable merge(Completable... other) {
return new MergeCompletable(false, this, executor, other);
}
/**
* Merges this {@link Completable} with the {@code other} {@link Completable}s so that the resulting
* {@link Completable} terminates successfully when all of these complete or terminates with an error when any one
* terminates with an error.
* <p>
* This method provides a means to merge multiple asynchronous sources, fails-fast in the presence of any errors,
* and in sequential programming is similar to:
* <pre>{@code
* ExecutorService e = ...;
* List<Future<Void>> futures = ...;
* futures.add(e.submit(() -> resultOfThisCompletable()));
* for (Completable c : other) {
* futures.add(e.submit(() -> resultOfCompletable(c));
* }
* // This is an approximation, this operator does not provide any ordering guarantees for the results.
* for (Future<Void> future : futures) {
* future.get(); // Throws if the processing for this item failed.
* }
* }</pre>
*
* @param other {@link Completable}s to merge.
* @return {@link Completable} that terminates successfully when this and all {@code other} {@link Completable}s
* complete or terminates with an error when any one terminates with an error.
*/
public final Completable merge(Iterable<? extends Completable> other) {
return new IterableMergeCompletable(false, this, other, executor);
}
/**
* Merges the passed {@link Publisher} with this {@link Completable}.
* <p>
* The resulting {@link Publisher} emits all items emitted by the passed {@link Publisher} and terminates
* successfully when both this {@link Completable} and the passed {@link Publisher} terminates successfully.
* It terminates with an error when any one of this {@link Completable} or passed {@link Publisher} terminates with
* an error.
* <pre>{@code
* ExecutorService e = ...;
* Future<?> future1 = e.submit(() -> resultOfThisCompletable()));
* Future<?> future2 = e.submit(() -> resultOfMergeWithStream());
* // This is an approximation, this operator does not provide any ordering guarantees for the results.
* future1.get(); // Throws if this Completable failed.
* future2.get(); // Throws if mergeWith Publisher failed.
* }</pre>
*
* @param mergeWith the {@link Publisher} to merge in
* @param <T> The value type of the resulting {@link Publisher}.
* @return {@link Publisher} that emits all items emitted by the passed {@link Publisher} and terminates
* successfully when both this {@link Completable} and the passed {@link Publisher} terminates successfully.
* It terminates with an error when any one of this {@link Completable} or passed {@link Publisher} terminates with
* an error.
*
* @see <a href="http://reactivex.io/documentation/operators/merge.html">ReactiveX merge operator.</a>
*/
public final <T> Publisher<T> merge(Publisher<? extends T> mergeWith) {
return new CompletableMergeWithPublisher<>(this, mergeWith, executor);
}
/**
* Merges this {@link Completable} with the {@code other} {@link Completable}s, and delays error notification until
* all involved {@link Completable}s terminate.
* <p>
* Use {@link #merge(Completable...)} if any error should immediately terminate the returned {@link Completable}.
* <p>
* This method provides a means to merge multiple asynchronous sources, delays throwing in the presence of any
* errors, and in sequential programming is similar to:
* <pre>{@code
* ExecutorService e = ...;
* List<Future<Void>> futures = ...;
* futures.add(e.submit(() -> resultOfThisCompletable()));
* for (Completable c : other) {
* futures.add(e.submit(() -> resultOfCompletable(c));
* }
* Throwable overallCause = null;
* // This is an approximation, this operator does not provide any ordering guarantees for the results.
* for (Future<Void> future : futures) {
* try {
* f.get();
* } catch (Throwable cause) {
* if (overallCause != null) {
* overallCause = cause;
* }
* }
* }
* if (overallCause != null) {
* throw overallCause;
* }
* }</pre>
*
* @param other {@link Completable}s to merge.
* @return {@link Completable} that terminates after {@code this} {@link Completable} and all {@code other}
* {@link Completable}s. If all involved {@link Completable}s terminate successfully then the return value will
* terminate successfully. If any {@link Completable} terminates in an error, then the return value will also
* terminate in an error.
*/
public final Completable mergeDelayError(Completable... other) {
return new MergeCompletable(true, this, executor, other);
}
/**
* Merges this {@link Completable} with the {@code other} {@link Completable}s, and delays error notification until
* all involved {@link Completable}s terminate.
* <p>
* Use {@link #merge(Iterable)} if any error should immediately terminate the returned {@link Completable}.
* <p>
* This method provides a means to merge multiple asynchronous sources, delays throwing in the presence of any
* errors, and in sequential programming is similar to:
* <pre>{@code
* ExecutorService e = ...;
* List<Future<Void>> futures = ...;
* futures.add(e.submit(() -> resultOfThisCompletable()));
* for (Completable c : other) {
* futures.add(e.submit(() -> resultOfCompletable(c));
* }
* Throwable overallCause = null;
* // This is an approximation, this operator does not provide any ordering guarantees for the results.
* for (Future<Void> future : futures) {
* try {
* f.get();
* } catch (Throwable cause) {
* if (overallCause != null) {
* overallCause = cause;
* }
* }
* }
* if (overallCause != null) {
* throw overallCause;
* }
* }</pre>
*
* @param other {@link Completable}s to merge.
* @return {@link Completable} that terminates after {@code this} {@link Completable} and all {@code other}
* {@link Completable}s. If all involved {@link Completable}s terminate successfully then the return value will
* terminate successfully. If any {@link Completable} terminates in an error, then the return value will also
* terminate in an error.
*/
public final Completable mergeDelayError(Iterable<? extends Completable> other) {
return new IterableMergeCompletable(true, this, other, executor);
}
/**
* Re-subscribes to this {@link Completable} if an error is emitted and the passed {@link BiIntPredicate} returns
* {@code true}.
* <p>
* This method provides a means to retry an operation under certain failure conditions and in sequential programming
* is similar to:
* <pre>{@code
* public T execute() {
* return execute(0);
* }
*
* private T execute(int attempts) {
* try {
* resultOfThisCompletable();
* } catch (Throwable cause) {
* if (shouldRetry.apply(attempts + 1, cause)) {
* return execute(attempts + 1);
* } else {
* throw cause;
* }
* }
* }
* }</pre>
*
* @param shouldRetry {@link BiIntPredicate} that given the retry count and the most recent {@link Throwable}
* emitted from this
* {@link Completable} determines if the operation should be retried.
* @return A {@link Completable} that completes with this {@link Completable} or re-subscribes if an error is
* emitted and if the passed {@link BiPredicate} returned {@code true}.
*
* @see <a href="http://reactivex.io/documentation/operators/retry.html">ReactiveX retry operator.</a>
*/
public final Completable retry(BiIntPredicate<Throwable> shouldRetry) {
return toSingle().retry(shouldRetry).ignoreElement();
}
/**
* Re-subscribes to this {@link Completable} if an error is emitted and the {@link Completable} returned by the
* supplied {@link BiIntFunction} completes successfully. If the returned {@link Completable} emits an error, the
* returned {@link Completable} terminates with that error.
* <p>
* This method provides a means to retry an operation under certain failure conditions in an asynchronous fashion
* and in sequential programming is similar to:
* <pre>{@code
* public T execute() {
* return execute(0);
* }
*
* private T execute(int attempts) {
* try {
* resultOfThisCompletable();
* } catch (Throwable cause) {
* try {
* shouldRetry.apply(attempts + 1, cause); // Either throws or completes normally
* execute(attempts + 1);
* } catch (Throwable ignored) {
* throw cause;
* }
* }
* }
* }</pre>
*
* @param retryWhen {@link BiIntFunction} that given the retry count and the most recent {@link Throwable} emitted
* from this {@link Completable} returns a {@link Completable}. If this {@link Completable} emits an error, that
* error is emitted from the returned {@link Completable}, otherwise, original {@link Completable} is re-subscribed
* when this {@link Completable} completes.
*
* @return A {@link Completable} that completes with this {@link Completable} or re-subscribes if an error is
* emitted and {@link Completable} returned by {@link BiFunction} completes successfully.
*
* @see <a href="http://reactivex.io/documentation/operators/retry.html">ReactiveX retry operator.</a>
*/
public final Completable retryWhen(BiIntFunction<Throwable, ? extends Completable> retryWhen) {
return toSingle().retryWhen(retryWhen).ignoreElement();
}
/**
* Re-subscribes to this {@link Completable} when it completes and the passed {@link IntPredicate} returns
* {@code true}.
* <p>
* This method provides a means to repeat an operation multiple times and in sequential programming is similar to:
* <pre>{@code
* int i = 0;
* do {
* resultOfThisCompletable();
* } while (shouldRepeat.test(++i));
* }</pre>
*
* @param shouldRepeat {@link IntPredicate} that given the repeat count determines if the operation should be
* repeated
* @return A {@link Publisher} that emits the value returned by the passed {@link Supplier} everytime this
* {@link Completable} completes.
*
* @see <a href="http://reactivex.io/documentation/operators/repeat.html">ReactiveX repeat operator.</a>
*/
public final Publisher<Void> repeat(IntPredicate shouldRepeat) {
return toSingle().repeat(shouldRepeat);
}
/**
* Re-subscribes to this {@link Completable} when it completes and the {@link Completable} returned by the supplied
* {@link IntFunction} completes successfully. If the returned {@link Completable} emits an error, the returned
* {@link Completable} emits an error.
* <p>
* This method provides a means to repeat an operation multiple times when in an asynchronous fashion and in
* sequential programming is similar to:
* <pre>{@code
* int i = 0;
* while (true) {
* resultOfThisCompletable();
* try {
* repeatWhen.apply(++i); // Either throws or completes normally
* } catch (Throwable cause) {
* break;
* }
* }
* }</pre>
*
* @param repeatWhen {@link IntFunction} that given the repeat count returns a {@link Completable}.
* If this {@link Completable} emits an error repeat is terminated, otherwise, original {@link Completable} is
* re-subscribed when this {@link Completable} completes.
* @return A {@link Completable} that completes after all re-subscriptions completes.
*
* @see <a href="http://reactivex.io/documentation/operators/retry.html">ReactiveX retry operator.</a>
*/
public final Publisher<Void> repeatWhen(IntFunction<? extends Completable> repeatWhen) {
return toSingle().repeatWhen(repeatWhen);
}
/**
* Invokes the {@code onSubscribe} {@link Consumer} argument <strong>before</strong>
* {@link Subscriber#onSubscribe(Cancellable)} is called for {@link Subscriber}s of the returned
* {@link Completable}.
*
* @param onSubscribe Invoked <strong>before</strong> {@link Subscriber#onSubscribe(Cancellable)} is called for
* {@link Subscriber}s of the returned {@link Completable}. <strong>MUST NOT</strong> throw.
* @return The new {@link Completable}.
*/
public final Completable beforeOnSubscribe(Consumer<Cancellable> onSubscribe) {
return beforeSubscriber(doOnSubscribeSupplier(onSubscribe));
}
/**
* Invokes the {@code onComplete} {@link Runnable} argument <strong>before</strong> {@link Subscriber#onComplete()}
* is called for {@link Subscriber}s of the returned {@link Completable}.
* <p>
* From a sequential programming point of view this method is roughly equivalent to the following:
* <pre>{@code
* resultOfThisCompletable();
* onComplete.run();
* nextOperation();
* }</pre>
*
* @param onComplete Invoked <strong>before</strong> {@link Subscriber#onComplete()} is called for
* {@link Subscriber}s of the returned {@link Completable}. <strong>MUST NOT</strong> throw.
* @return The new {@link Completable}.
*/
public final Completable beforeOnComplete(Runnable onComplete) {
return beforeSubscriber(doOnCompleteSupplier(onComplete));
}
/**
* Invokes the {@code onError} {@link Consumer} argument <strong>before</strong>
* {@link Subscriber#onError(Throwable)} is called for {@link Subscriber}s of the returned {@link Completable}.
* <p>
* From a sequential programming point of view this method is roughly equivalent to the following:
* <pre>{@code
* try {
* resultOfThisCompletable();
* } catch (Throwable cause) {
* onError.accept(cause);
* nextOperation(cause);
* }
* }</pre>
*
* @param onError Invoked <strong>before</strong> {@link Subscriber#onError(Throwable)} is called for
* {@link Subscriber}s of the returned {@link Completable}. <strong>MUST NOT</strong> throw.
* @return The new {@link Completable}.
*/
public final Completable beforeOnError(Consumer<Throwable> onError) {
return beforeSubscriber(doOnErrorSupplier(onError));
}
/**
* Invokes the {@code onCancel} {@link Runnable} argument <strong>before</strong> {@link Cancellable#cancel()} is
* called for Subscriptions of the returned {@link Completable}.
*
* @param onCancel Invoked <strong>before</strong> {@link Cancellable#cancel()} is called for Subscriptions of the
* returned {@link Completable}. <strong>MUST NOT</strong> throw.
* @return The new {@link Completable}.
*/
public final Completable beforeCancel(Runnable onCancel) {
return new DoCancellableCompletable(this, onCancel::run, true, executor);
}
/**
* Invokes the {@code whenFinally} {@link Runnable} argument <strong>before</strong> any of the following terminal
* methods are called:
* <ul>
* <li>{@link Subscriber#onComplete()}</li>
* <li>{@link Subscriber#onError(Throwable)}</li>
* <li>{@link Cancellable#cancel()}</li>
* </ul>
* for Subscriptions/{@link Subscriber}s of the returned {@link Completable}.
* <pre>{@code
* try {
* resultOfThisCompletable();
* } finally {
* whenFinally.run();
* nextOperation(); // Maybe notifying of cancellation, or termination
* }
* }</pre>
*
* @param doFinally Invoked <strong>before</strong> any of the following terminal methods are called:
* <ul>
* <li>{@link Subscriber#onComplete()}</li>
* <li>{@link Subscriber#onError(Throwable)}</li>
* <li>{@link Cancellable#cancel()}</li>
* </ul>
* for Subscriptions/{@link Subscriber}s of the returned {@link Completable}. <strong>MUST NOT</strong> throw.
* @return The new {@link Completable}.
*/
public final Completable beforeFinally(Runnable doFinally) {
return new BeforeFinallyCompletable(this, doFinally, executor);
}
/**
* Creates a new {@link Subscriber} (via the {@code subscriberSupplier} argument) on each call to
* subscribe and invokes all the {@link Subscriber} methods <strong>before</strong> the {@link Subscriber}s of the
* returned {@link Completable}.
*
* @param subscriberSupplier Creates a new {@link Subscriber} on each call to subscribe and invokes all the
* {@link Subscriber} methods <strong>before</strong> the {@link Subscriber}s of the returned {@link Completable}.
* {@link Subscriber} methods <strong>MUST NOT</strong> throw.
* @return The new {@link Completable}.
*/
public final Completable beforeSubscriber(Supplier<? extends Subscriber> subscriberSupplier) {
return new BeforeSubscriberCompletable(this, subscriberSupplier, executor);
}
/**
* Invokes the {@code onSubscribe} {@link Consumer} argument <strong>after</strong>
* {@link Subscriber#onSubscribe(Cancellable)} is called for {@link Subscriber}s of the returned
* {@link Completable}.
*
* @param onSubscribe Invoked <strong>after</strong> {@link Subscriber#onSubscribe(Cancellable)} is called for
* {@link Subscriber}s of the returned {@link Completable}. <strong>MUST NOT</strong> throw.
* @return The new {@link Completable}.
*/
public final Completable afterOnSubscribe(Consumer<Cancellable> onSubscribe) {
return afterSubscriber(doOnSubscribeSupplier(onSubscribe));
}
/**
* Invokes the {@code onSubscribe} {@link Consumer} argument when
* {@link Subscriber#onSubscribe(Cancellable)} is called for {@link Subscriber}s of the returned
* {@link Completable}.
* <p>
* The order in which {@code onSubscribe} will be invoked relative to
* {@link Subscriber#onSubscribe(Cancellable)} is undefined. If you need strict ordering see
* {@link #beforeOnSubscribe(Consumer)} and {@link #afterOnSubscribe(Consumer)}.
*
* @param onSubscribe Invoked when {@link Subscriber#onSubscribe(Cancellable)} is called for
* {@link Subscriber}s of the returned {@link Completable}. <strong>MUST NOT</strong> throw.
* @return The new {@link Completable}.
*
* @see #beforeOnSubscribe(Consumer)
* @see #afterOnSubscribe(Consumer)
*/
public final Completable whenOnSubscribe(Consumer<Cancellable> onSubscribe) {
return afterOnSubscribe(onSubscribe);
}
/**
* Invokes the {@code onComplete} {@link Runnable} argument <strong>after</strong> {@link Subscriber#onComplete()}
* is called for {@link Subscriber}s of the returned {@link Completable}.
* <p>
* From a sequential programming point of view this method is roughly equivalent to the following:
* <pre>{@code
* resultOfThisCompletable();
* nextOperation();
* onComplete.run();
* }</pre>
*
* @param onComplete Invoked <strong>after</strong> {@link Subscriber#onComplete()} is called for
* {@link Subscriber}s of the returned {@link Completable}. <strong>MUST NOT</strong> throw.
* @return The new {@link Completable}.
*/
public final Completable afterOnComplete(Runnable onComplete) {
return afterSubscriber(doOnCompleteSupplier(onComplete));
}
/**
* Invokes the {@code onError} {@link Consumer} argument <strong>after</strong>
* {@link Subscriber#onError(Throwable)} is called for {@link Subscriber}s of the returned {@link Completable}.
* <p>
* From a sequential programming point of view this method is roughly equivalent to the following:
* <pre>{@code
* try {
* resultOfThisCompletable();
* } catch (Throwable cause) {
* nextOperation(cause);
* onError.accept(cause);
* }
* }</pre>
*
* @param onError Invoked <strong>after</strong> {@link Subscriber#onError(Throwable)} is called for
* {@link Subscriber}s of the returned {@link Completable}. <strong>MUST NOT</strong> throw.
* @return The new {@link Completable}.
*/
public final Completable afterOnError(Consumer<Throwable> onError) {
return afterSubscriber(doOnErrorSupplier(onError));
}
/**
* Invokes the {@code onCancel} {@link Runnable} argument <strong>after</strong> {@link Cancellable#cancel()} is
* called for Subscriptions of the returned {@link Completable}.
*
* @param onCancel Invoked <strong>after</strong> {@link Cancellable#cancel()} is called for Subscriptions of the
* returned {@link Completable}. <strong>MUST NOT</strong> throw.
* @return The new {@link Completable}.
*/
public final Completable afterCancel(Runnable onCancel) {
return new DoCancellableCompletable(this, onCancel::run, false, executor);
}
/**
* Invokes the {@code whenFinally} {@link Runnable} argument <strong>after</strong> any of the following terminal
* methods are called:
* <ul>
* <li>{@link Subscriber#onComplete()}</li>
* <li>{@link Subscriber#onError(Throwable)}</li>
* <li>{@link Cancellable#cancel()}</li>
* </ul>
* for Subscriptions/{@link Subscriber}s of the returned {@link Completable}.
* <p>
* From a sequential programming point of view this method is roughly equivalent to the following:
* <pre>{@code
* try {
* resultOfThisCompletable();
* } finally {
* nextOperation(); // Maybe notifying of cancellation, or termination
* whenFinally.run();
* }
* }</pre>
*
* @param doFinally Invoked <strong>after</strong> any of the following terminal methods are called:
* <ul>
* <li>{@link Subscriber#onComplete()}</li>
* <li>{@link Subscriber#onError(Throwable)}</li>
* <li>{@link Cancellable#cancel()}</li>
* </ul>
* for Subscriptions/{@link Subscriber}s of the returned {@link Completable}. <strong>MUST NOT</strong> throw.
* @return The new {@link Completable}.
*/
public final Completable afterFinally(Runnable doFinally) {
return new AfterFinallyCompletable(this, doFinally, executor);
}
/**
* Creates a new {@link Subscriber} (via the {@code subscriberSupplier} argument) on each call to
* subscribe and invokes all the {@link Subscriber} methods <strong>after</strong> the {@link Subscriber}s of the
* returned {@link Completable}.
*
* @param subscriberSupplier Creates a new {@link Subscriber} on each call to subscribe and invokes all the
* {@link Subscriber} methods <strong>after</strong> the {@link Subscriber}s of the returned {@link Completable}.
* {@link Subscriber} methods <strong>MUST NOT</strong> throw.
* @return The new {@link Completable}.
*/
public final Completable afterSubscriber(Supplier<? extends Subscriber> subscriberSupplier) {
return new AfterSubscriberCompletable(this, subscriberSupplier, executor);
}
/**
* Creates a new {@link Subscriber} (via the {@code subscriberSupplier} argument) for each new subscribe and
* invokes methods on that {@link Subscriber} when the corresponding methods are called for {@link Subscriber}s of
* the returned {@link Publisher}.
*
* @param subscriberSupplier Creates a new {@link Subscriber} for each new subscribe and invokes methods on that
* {@link Subscriber} when the corresponding methods are called for {@link Subscriber}s of the returned
* {@link Publisher}. {@link Subscriber} methods <strong>MUST NOT</strong> throw.
* @return The new {@link Completable}.
*/
public final Completable whenSubscriber(Supplier<? extends Subscriber> subscriberSupplier) {
return afterSubscriber(subscriberSupplier);
}
/**
* <strong>This method requires advanced knowledge of building operators. Before using this method please attempt
* to compose existing operator(s) to satisfy your use case.</strong>
* <p>
* Returns a {@link Completable} which will wrap the {@link Subscriber} using the provided {@code operator} argument
* before subscribing to this {@link Completable}.
* <pre>{@code
* Completable<X> pub = ...;
* pub.map(..) // A
* .liftSync(original -> modified)
* .afterFinally(..) // B
* }</pre>
* The {@code original -> modified} "operator" <strong>MUST</strong> be "synchronous" in that it does not interact
* with the original {@link Subscriber} from outside the modified {@link Subscriber} or {@link Cancellable}
* threads. That is to say this operator will not impact the {@link Executor} constraints already in place between
* <i>A</i> and <i>B</i> above. If you need asynchronous behavior, or are unsure, see
* {@link #liftAsync(CompletableOperator)}.
*
* @param operator The custom operator logic. The input is the "original" {@link Subscriber} to this
* {@link Completable} and the return is the "modified" {@link Subscriber} that provides custom operator business
* logic.
* @return a {@link Completable} that when subscribed, the {@code operator} argument will be used to wrap the
* {@link Subscriber} before subscribing to this {@link Completable}.
* @see #liftAsync(CompletableOperator)
*/
public final Completable liftSync(CompletableOperator operator) {
return new LiftSynchronousCompletableOperator(this, operator, executor);
}
/**
* <strong>This method requires advanced knowledge of building operators. Before using this method please attempt
* to compose existing operator(s) to satisfy your use case.</strong>
* <p>
* Returns a {@link Completable} which will wrap the {@link Subscriber} using the provided {@code operator} argument
* before subscribing to this {@link Completable}.
* <pre>{@code
* Publisher<X> pub = ...;
* pub.map(..) // A
* .liftAsync(original -> modified)
* .afterFinally(..) // B
* }</pre>
*
* The {@code original -> modified} "operator" MAY be "asynchronous" in that it may interact with the original
* {@link Subscriber} from outside the modified {@link Subscriber} or {@link Cancellable} threads. More
* specifically:
* <ul>
* <li>all of the {@link Subscriber} invocations going "downstream" (i.e. from <i>A</i> to <i>B</i> above) MAY be
* offloaded via an {@link Executor}</li>
* <li>all of the {@link Cancellable} invocations going "upstream" (i.e. from <i>B</i> to <i>A</i> above) MAY be
* offloaded via an {@link Executor}</li>
* </ul>
* This behavior exists to prevent blocking code negatively impacting the thread that powers the upstream source of
* data (e.g. an EventLoop).
* @param operator The custom operator logic. The input is the "original" {@link Subscriber} to this
* {@link Completable} and the return is the "modified" {@link Subscriber} that provides custom operator business
* logic.
* @return a {@link Completable} that when subscribed, the {@code operator} argument will be used to wrap the
* {@link Subscriber} before subscribing to this {@link Completable}.
* @see #liftSync(CompletableOperator)
*/
public final Completable liftAsync(CompletableOperator operator) {
return new LiftAsynchronousCompletableOperator(this, operator, executor);
}
/**
* Creates a new {@link Completable} that will use the passed {@link Executor} to invoke all {@link Subscriber}
* methods.
* This method does <strong>not</strong> override preceding {@link Executor}s, if any, specified for {@code this}
* {@link Completable}. Only subsequent operations, if any, added in this execution chain will use this
* {@link Executor}. If such an override is required, {@link #publishOnOverride(Executor)} can be used.
*
* @param executor {@link Executor} to use.
* @return A new {@link Completable} that will use the passed {@link Executor} to invoke all methods on the
* {@link Subscriber}.
*/