-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Mono.java
5375 lines (5122 loc) · 226 KB
/
Mono.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 (c) 2016-2023 VMware Inc. or its affiliates, All Rights Reserved.
*
* 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
*
* https://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 reactor.core.publisher;
import java.time.Duration;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.Spliterator;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.BiPredicate;
import java.util.function.BooleanSupplier;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.LongConsumer;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.logging.Level;
import io.micrometer.core.instrument.MeterRegistry;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import reactor.core.CorePublisher;
import reactor.core.CoreSubscriber;
import reactor.core.Disposable;
import reactor.core.Exceptions;
import reactor.core.Fuseable;
import reactor.core.Scannable;
import reactor.core.publisher.FluxOnAssembly.AssemblySnapshot;
import reactor.core.publisher.FluxOnAssembly.CheckpointHeavySnapshot;
import reactor.core.publisher.FluxOnAssembly.CheckpointLightSnapshot;
import reactor.core.scheduler.Scheduler;
import reactor.core.scheduler.Scheduler.Worker;
import reactor.core.scheduler.Schedulers;
import reactor.util.Logger;
import reactor.util.Metrics;
import reactor.util.annotation.Nullable;
import reactor.util.concurrent.Queues;
import reactor.util.context.Context;
import reactor.util.context.ContextView;
import reactor.util.function.Tuple2;
import reactor.util.function.Tuple3;
import reactor.util.function.Tuple4;
import reactor.util.function.Tuple5;
import reactor.util.function.Tuple6;
import reactor.util.function.Tuple7;
import reactor.util.function.Tuple8;
import reactor.util.function.Tuples;
import reactor.core.observability.SignalListener;
import reactor.core.observability.SignalListenerFactory;
import reactor.util.retry.Retry;
/**
* A Reactive Streams {@link Publisher} with basic rx operators that emits at most one item <em>via</em> the
* {@code onNext} signal then terminates with an {@code onComplete} signal (successful Mono,
* with or without value), or only emits a single {@code onError} signal (failed Mono).
*
* <p>Most Mono implementations are expected to immediately call {@link Subscriber#onComplete()}
* after having called {@link Subscriber#onNext(T)}. {@link Mono#never() Mono.never()} is an outlier: it doesn't
* emit any signal, which is not technically forbidden although not terribly useful outside
* of tests. On the other hand, a combination of {@code onNext} and {@code onError} is explicitly forbidden.
*
* <p>
* The recommended way to learn about the {@link Mono} API and discover new operators is
* through the reference documentation, rather than through this javadoc (as opposed to
* learning more about individual operators). See the <a href="https://projectreactor.io/docs/core/release/reference/docs/index.html#which-operator">
* "which operator do I need?" appendix</a>.
*
* <p><img class="marble" src="doc-files/marbles/mono.svg" alt="">
*
* <p>
*
* <p>The rx operators will offer aliases for input {@link Mono} type to preserve the "at most one"
* property of the resulting {@link Mono}. For instance {@link Mono#flatMap flatMap} returns a
* {@link Mono}, while there is a {@link Mono#flatMapMany flatMapMany} alias with possibly more than
* 1 emission.
*
* <p>{@code Mono<Void>} should be used for {@link Publisher} that just completes without any value.
*
* <p>It is intended to be used in implementations and return types, input parameters should keep
* using raw {@link Publisher} as much as possible.
*
* <p>Note that using state in the {@code java.util.function} / lambdas used within Mono operators
* should be avoided, as these may be shared between several {@link Subscriber Subscribers}.
*
* @param <T> the type of the single value of this class
* @author Sebastien Deleuze
* @author Stephane Maldini
* @author David Karnok
* @author Simon Baslé
* @see Flux
*/
public abstract class Mono<T> implements CorePublisher<T> {
// ==============================================================================================================
// Static Generators
// ==============================================================================================================
/**
* Creates a deferred emitter that can be used with callback-based
* APIs to signal at most one value, a complete or an error signal.
* <p>
* <img class="marble" src="doc-files/marbles/createForMono.svg" alt="">
* <p>
* Bridging legacy API involves mostly boilerplate code due to the lack
* of standard types and methods. There are two kinds of API surfaces:
* 1) addListener/removeListener and 2) callback-handler.
* <p>
* <b>1) addListener/removeListener pairs</b><br>
* To work with such API one has to instantiate the listener,
* call the sink from the listener then register it with the source:
* <pre><code>
* Mono.<String>create(sink -> {
* HttpListener listener = event -> {
* if (event.getResponseCode() >= 400) {
* sink.error(new RuntimeException("Failed"));
* } else {
* String body = event.getBody();
* if (body.isEmpty()) {
* sink.success();
* } else {
* sink.success(body.toLowerCase());
* }
* }
* };
*
* client.addListener(listener);
*
* sink.onDispose(() -> client.removeListener(listener));
* });
* </code></pre>
* Note that this works only with single-value emitting listeners. Otherwise,
* all subsequent signals are dropped. You may have to add {@code client.removeListener(this);}
* to the listener's body.
* <p>
* <b>2) callback handler</b><br>
* This requires a similar instantiation pattern such as above, but usually the
* successful completion and error are separated into different methods.
* In addition, the legacy API may or may not support some cancellation mechanism.
* <pre><code>
* Mono.<String>create(sink -> {
* Callback<String> callback = new Callback<String>() {
* @Override
* public void onResult(String data) {
* sink.success(data.toLowerCase());
* }
*
* @Override
* public void onError(Exception e) {
* sink.error(e);
* }
* }
*
* // without cancellation support:
*
* client.call("query", callback);
*
* // with cancellation support:
*
* AutoCloseable cancel = client.call("query", callback);
* sink.onDispose(() -> {
* try {
* cancel.close();
* } catch (Exception ex) {
* Exceptions.onErrorDropped(ex);
* }
* });
* });
* </code></pre>
* @param callback Consume the {@link MonoSink} provided per-subscriber by Reactor to generate signals.
* @param <T> The type of the value emitted
* @return a {@link Mono}
*/
public static <T> Mono<T> create(Consumer<MonoSink<T>> callback) {
return onAssembly(new MonoCreate<>(callback));
}
/**
* Create a {@link Mono} provider that will {@link Supplier#get supply} a target {@link Mono} to subscribe to for
* each {@link Subscriber} downstream.
*
* <p>
* <img class="marble" src="doc-files/marbles/deferForMono.svg" alt="">
* <p>
* @param supplier a {@link Mono} factory
* @param <T> the element type of the returned Mono instance
* @return a deferred {@link Mono}
* @see #deferContextual(Function)
*/
public static <T> Mono<T> defer(Supplier<? extends Mono<? extends T>> supplier) {
return onAssembly(new MonoDefer<>(supplier));
}
/**
* Create a {@link Mono} provider that will {@link Function#apply supply} a target {@link Mono}
* to subscribe to for each {@link Subscriber} downstream.
* This operator behaves the same way as {@link #defer(Supplier)},
* but accepts a {@link Function} that will receive the current {@link ContextView} as an argument.
*
* <p>
* <img class="marble" src="doc-files/marbles/deferForMono.svg" alt="">
* <p>
* @param contextualMonoFactory a {@link Mono} factory
* @param <T> the element type of the returned Mono instance
* @return a deferred {@link Mono} deriving actual {@link Mono} from context values for each subscription
*/
public static <T> Mono<T> deferContextual(Function<ContextView, ? extends Mono<? extends T>> contextualMonoFactory) {
return onAssembly(new MonoDeferContextual<>(contextualMonoFactory));
}
/**
* Create a Mono which delays an onNext signal by a given {@link Duration duration}
* on a default Scheduler and completes.
* If the demand cannot be produced in time, an onError will be signalled instead.
* The delay is introduced through the {@link Schedulers#parallel() parallel} default Scheduler.
*
* <p>
* <img class="marble" src="doc-files/marbles/delay.svg" alt="">
* <p>
* @param duration the duration of the delay
*
* @return a new {@link Mono}
*/
public static Mono<Long> delay(Duration duration) {
return delay(duration, Schedulers.parallel());
}
/**
* Create a Mono which delays an onNext signal by a given {@link Duration duration}
* on a provided {@link Scheduler} and completes.
* If the demand cannot be produced in time, an onError will be signalled instead.
*
* <p>
* <img class="marble" src="doc-files/marbles/delay.svg" alt="">
* <p>
* @param duration the {@link Duration} of the delay
* @param timer a time-capable {@link Scheduler} instance to run on
*
* @return a new {@link Mono}
*/
public static Mono<Long> delay(Duration duration, Scheduler timer) {
return onAssembly(new MonoDelay(duration.toNanos(), TimeUnit.NANOSECONDS, timer));
}
/**
* Create a {@link Mono} that completes without emitting any item.
*
* <p>
* <img class="marble" src="doc-files/marbles/empty.svg" alt="">
* <p>
* @param <T> the reified {@link Subscriber} type
*
* @return a completed {@link Mono}
*/
public static <T> Mono<T> empty() {
return MonoEmpty.instance();
}
/**
* Create a {@link Mono} that terminates with the specified error immediately after
* being subscribed to.
* <p>
* <img class="marble" src="doc-files/marbles/error.svg" alt="">
* <p>
* @param error the onError signal
* @param <T> the reified {@link Subscriber} type
*
* @return a failing {@link Mono}
*/
public static <T> Mono<T> error(Throwable error) {
return onAssembly(new MonoError<>(error));
}
/**
* Create a {@link Mono} that terminates with an error immediately after being
* subscribed to. The {@link Throwable} is generated by a {@link Supplier}, invoked
* each time there is a subscription and allowing for lazy instantiation.
* <p>
* <img class="marble" src="doc-files/marbles/errorWithSupplier.svg" alt="">
* <p>
* @param errorSupplier the error signal {@link Supplier} to invoke for each {@link Subscriber}
* @param <T> the reified {@link Subscriber} type
*
* @return a failing {@link Mono}
*/
public static <T> Mono<T> error(Supplier<? extends Throwable> errorSupplier) {
return onAssembly(new MonoErrorSupplied<>(errorSupplier));
}
/**
* Pick the first {@link Mono} to emit any signal (value, empty completion or error)
* and replay that signal, effectively behaving like the fastest of these competing
* sources.
* <p>
* <img class="marble" src="doc-files/marbles/firstWithSignalForMono.svg" alt="">
* <p>
* @param monos The deferred monos to use.
* @param <T> The type of the function result.
*
* @return a new {@link Mono} behaving like the fastest of its sources.
* @deprecated use {@link #firstWithSignal(Mono[])}. To be removed in reactor 3.5.
*/
@SafeVarargs
@Deprecated
public static <T> Mono<T> first(Mono<? extends T>... monos) {
return firstWithSignal(monos);
}
/**
* Pick the first {@link Mono} to emit any signal (value, empty completion or error)
* and replay that signal, effectively behaving like the fastest of these competing
* sources.
* <p>
* <img class="marble" src="doc-files/marbles/firstWithSignalForMono.svg" alt="">
* <p>
* @param monos The deferred monos to use.
* @param <T> The type of the function result.
*
* @return a new {@link Mono} behaving like the fastest of its sources.
* @deprecated use {@link #firstWithSignal(Iterable)}. To be removed in reactor 3.5.
*/
@Deprecated
public static <T> Mono<T> first(Iterable<? extends Mono<? extends T>> monos) {
return firstWithSignal(monos);
}
/**
* Pick the first {@link Mono} to emit any signal (value, empty completion or error)
* and replay that signal, effectively behaving like the fastest of these competing
* sources.
* <p>
* <img class="marble" src="doc-files/marbles/firstWithSignalForMono.svg" alt="">
* <p>
* @param monos The deferred monos to use.
* @param <T> The type of the function result.
*
* @return a new {@link Mono} behaving like the fastest of its sources.
*/
@SafeVarargs
public static <T> Mono<T> firstWithSignal(Mono<? extends T>... monos) {
return onAssembly(new MonoFirstWithSignal<>(monos));
}
/**
* Pick the first {@link Mono} to emit any signal (value, empty completion or error)
* and replay that signal, effectively behaving like the fastest of these competing
* sources.
* <p>
* <img class="marble" src="doc-files/marbles/firstWithSignalForMono.svg" alt="">
* <p>
* @param monos The deferred monos to use.
* @param <T> The type of the function result.
*
* @return a new {@link Mono} behaving like the fastest of its sources.
*/
public static <T> Mono<T> firstWithSignal(Iterable<? extends Mono<? extends T>> monos) {
return onAssembly(new MonoFirstWithSignal<>(monos));
}
/**
* Pick the first {@link Mono} source to emit any value and replay that signal,
* effectively behaving like the source that first emits an
* {@link Subscriber#onNext(Object) onNext}.
*
* <p>
* Valued sources always "win" over an empty source (one that only emits onComplete)
* or a failing source (one that only emits onError).
* <p>
* When no source can provide a value, this operator fails with a {@link NoSuchElementException}
* (provided there are at least two sources). This exception has a {@link Exceptions#multiple(Throwable...) composite}
* as its {@link Throwable#getCause() cause} that can be used to inspect what went wrong with each source
* (so the composite has as many elements as there are sources).
* <p>
* Exceptions from failing sources are directly reflected in the composite at the index of the failing source.
* For empty sources, a {@link NoSuchElementException} is added at their respective index.
* One can use {@link Exceptions#unwrapMultiple(Throwable) Exceptions.unwrapMultiple(topLevel.getCause())}
* to easily inspect these errors as a {@link List}.
* <p>
* Note that like in {@link #firstWithSignal(Iterable)}, an infinite source can be problematic
* if no other source emits onNext.
* <p>
* <img class="marble" src="doc-files/marbles/firstWithValueForMono.svg" alt="">
*
* @param monos An {@link Iterable} of the competing source monos
* @param <T> The type of the element in the sources and the resulting mono
*
* @return a new {@link Mono} behaving like the fastest of its sources
*/
public static <T> Mono<T> firstWithValue(Iterable<? extends Mono<? extends T>> monos) {
return onAssembly(new MonoFirstWithValue<>(monos));
}
/**
* Pick the first {@link Mono} source to emit any value and replay that signal,
* effectively behaving like the source that first emits an
* {@link Subscriber#onNext(Object) onNext}.
* <p>
* Valued sources always "win" over an empty source (one that only emits onComplete)
* or a failing source (one that only emits onError).
* <p>
* When no source can provide a value, this operator fails with a {@link NoSuchElementException}
* (provided there are at least two sources). This exception has a {@link Exceptions#multiple(Throwable...) composite}
* as its {@link Throwable#getCause() cause} that can be used to inspect what went wrong with each source
* (so the composite has as many elements as there are sources).
* <p>
* Exceptions from failing sources are directly reflected in the composite at the index of the failing source.
* For empty sources, a {@link NoSuchElementException} is added at their respective index.
* One can use {@link Exceptions#unwrapMultiple(Throwable) Exceptions.unwrapMultiple(topLevel.getCause())}
* to easily inspect these errors as a {@link List}.
* <p>
* Note that like in {@link #firstWithSignal(Mono[])}, an infinite source can be problematic
* if no other source emits onNext.
* In case the {@code first} source is already an array-based {@link #firstWithValue(Mono, Mono[])}
* instance, nesting is avoided: a single new array-based instance is created with all the
* sources from {@code first} plus all the {@code others} sources at the same level.
* <p>
* <img class="marble" src="doc-files/marbles/firstWithValueForMono.svg" alt="">
*
* @param first the first competing source {@link Mono}
* @param others the other competing sources {@link Mono}
* @param <T> The type of the element in the sources and the resulting mono
*
* @return a new {@link Mono} behaving like the fastest of its sources
*/
@SafeVarargs
public static <T> Mono<T> firstWithValue(Mono<? extends T> first, Mono<? extends T>... others) {
if (first instanceof MonoFirstWithValue) {
@SuppressWarnings("unchecked")
MonoFirstWithValue<T> a = (MonoFirstWithValue<T>) first;
Mono<T> result = a.firstValuedAdditionalSources(others);
if (result != null) {
return result;
}
}
return onAssembly(new MonoFirstWithValue<>(first, others));
}
/**
* Expose the specified {@link Publisher} with the {@link Mono} API, and ensure it will emit 0 or 1 item.
* The source emitter will be cancelled on the first `onNext`.
* <p>
* <img class="marble" src="doc-files/marbles/fromForMono.svg" alt="">
* <p>
* {@link Hooks#onEachOperator(String, Function)} and similar assembly hooks are applied
* unless the source is already a {@link Mono} (including {@link Mono} that was decorated as a {@link Flux},
* see {@link Flux#from(Publisher)}).
*
* @param source the {@link Publisher} source
* @param <T> the source type
*
* @return the next item emitted as a {@link Mono}
*/
public static <T> Mono<T> from(Publisher<? extends T> source) {
//some sources can be considered already assembled monos
//all conversion methods (from, fromDirect, wrap) must accommodate for this
if (source instanceof Mono) {
@SuppressWarnings("unchecked")
Mono<T> casted = (Mono<T>) source;
return casted;
}
if (source instanceof FluxSourceMono
|| source instanceof FluxSourceMonoFuseable) {
@SuppressWarnings("unchecked")
FluxFromMonoOperator<T, T> wrapper = (FluxFromMonoOperator<T,T>) source;
@SuppressWarnings("unchecked")
Mono<T> extracted = (Mono<T>) wrapper.source;
return extracted;
}
//we delegate to `wrap` and apply assembly hooks
@SuppressWarnings("unchecked") Publisher<T> downcasted = (Publisher<T>) source;
return onAssembly(wrap(downcasted, true));
}
/**
* Create a {@link Mono} producing its value using the provided {@link Callable}. If
* the Callable resolves to {@code null}, the resulting Mono completes empty.
*
* <p>
* <img class="marble" src="doc-files/marbles/fromCallable.svg" alt="">
* <p>
* @param supplier {@link Callable} that will produce the value
* @param <T> type of the expected value
*
* @return A {@link Mono}.
*/
public static <T> Mono<T> fromCallable(Callable<? extends T> supplier) {
return onAssembly(new MonoCallable<>(supplier));
}
/**
* Create a {@link Mono}, producing its value using the provided {@link CompletionStage}.
*
* <p>
* <img class="marble" src="doc-files/marbles/fromFuture.svg" alt="">
* <p>
* If the completionStage is also a {@link Future}, cancelling the Mono will cancel the future.
* Use {@link #fromFuture(CompletableFuture, boolean)} with {@code suppressCancellation} set to
* {@code true} if you need to suppress cancellation propagation.
*
* @param completionStage {@link CompletionStage} that will produce a value (or a null to
* complete immediately)
* @param <T> type of the expected value
* @return A {@link Mono}.
*/
public static <T> Mono<T> fromCompletionStage(CompletionStage<? extends T> completionStage) {
return onAssembly(new MonoCompletionStage<>(completionStage, false));
}
/**
* Create a {@link Mono} that wraps a lazily-supplied {@link CompletionStage} on subscription,
* emitting the value produced by the {@link CompletionStage}.
*
* <p>
* <img class="marble" src="doc-files/marbles/fromFutureSupplier.svg" alt="">
* <p>
* If the completionStage is also a {@link Future}, cancelling the Mono will cancel the future.
* Use {@link #fromFuture(CompletableFuture, boolean)} with {@code suppressCancellation} set to
* {@code true} if you need to suppress cancellation propagation.
*
* @param stageSupplier The {@link Supplier} of a {@link CompletionStage} that will produce a value (or a null to
* complete immediately). This allows lazy triggering of CompletionStage-based APIs.
* @param <T> type of the expected value
* @return A {@link Mono}.
*/
public static <T> Mono<T> fromCompletionStage(Supplier<? extends CompletionStage<? extends T>> stageSupplier) {
return defer(() -> onAssembly(new MonoCompletionStage<>(stageSupplier.get(), false)));
}
/**
* Convert a {@link Publisher} to a {@link Mono} without any cardinality check
* (ie this method doesn't cancel the source past the first element).
* Conversion transparently returns {@link Mono} sources without wrapping and otherwise
* supports {@link Fuseable} sources.
* Note this is an advanced interoperability operator that implies you know the
* {@link Publisher} you are converting follows the {@link Mono} semantics and only
* ever emits one element.
* <p>
* {@link Hooks#onEachOperator(String, Function)} and similar assembly hooks are applied
* unless the source is already a {@link Mono}.
*
* @param source the Mono-compatible {@link Publisher} to wrap
* @param <I> type of the value emitted by the publisher
* @return a wrapped {@link Mono}
*/
public static <I> Mono<I> fromDirect(Publisher<? extends I> source){
//some sources can be considered already assembled monos
//all conversion methods (from, fromDirect, wrap) must accommodate for this
if(source instanceof Mono){
@SuppressWarnings("unchecked")
Mono<I> m = (Mono<I>)source;
return m;
}
if (source instanceof FluxSourceMono
|| source instanceof FluxSourceMonoFuseable) {
@SuppressWarnings("unchecked")
FluxFromMonoOperator<I, I> wrapper = (FluxFromMonoOperator<I,I>) source;
@SuppressWarnings("unchecked")
Mono<I> extracted = (Mono<I>) wrapper.source;
return extracted;
}
//we delegate to `wrap` and apply assembly hooks
@SuppressWarnings("unchecked") Publisher<I> downcasted = (Publisher<I>) source;
return onAssembly(wrap(downcasted, false));
}
/**
* Create a {@link Mono}, producing its value using the provided {@link CompletableFuture}
* and cancelling the future if the Mono gets cancelled.
*
* <p>
* <img class="marble" src="doc-files/marbles/fromFuture.svg" alt="">
* <p>
* Use {@link #fromFuture(CompletableFuture, boolean)} with {@code suppressCancellation} set to
* {@code true} if you need to suppress cancellation propagation.
*
* @param future {@link CompletableFuture} that will produce a value (or a null to
* complete immediately)
* @param <T> type of the expected value
* @return A {@link Mono}.
* @see #fromCompletionStage(CompletionStage) fromCompletionStage for a generalization
*/
public static <T> Mono<T> fromFuture(CompletableFuture<? extends T> future) {
return fromFuture(future, false);
}
/**
* Create a {@link Mono}, producing its value using the provided {@link CompletableFuture}
* and optionally cancelling the future if the Mono gets cancelled (if {@code suppressCancel == false}).
*
* <p>
* <img class="marble" src="doc-files/marbles/fromFuture.svg" alt="">
* <p>
*
* @param future {@link CompletableFuture} that will produce a value (or a null to complete immediately)
* @param suppressCancel {@code true} to prevent cancellation of the future when the Mono is cancelled,
* {@code false} otherwise (the default)
* @param <T> type of the expected value
* @return A {@link Mono}.
*/
public static <T> Mono<T> fromFuture(CompletableFuture<? extends T> future, boolean suppressCancel) {
return onAssembly(new MonoCompletionStage<>(future, suppressCancel));
}
/**
* Create a {@link Mono} that wraps a lazily-supplied {@link CompletableFuture} on subscription,
* emitting the value produced by the future and cancelling the future if the Mono gets cancelled.
*
* <p>
* <img class="marble" src="doc-files/marbles/fromFutureSupplier.svg" alt="">
* <p>
*
* @param futureSupplier The {@link Supplier} of a {@link CompletableFuture} that will produce a value
* (or a null to complete immediately). This allows lazy triggering of future-based APIs.
* @param <T> type of the expected value
* @return A {@link Mono}.
* @see #fromCompletionStage(Supplier) fromCompletionStage for a generalization
*/
public static <T> Mono<T> fromFuture(Supplier<? extends CompletableFuture<? extends T>> futureSupplier) {
return fromFuture(futureSupplier, false);
}
/**
* Create a {@link Mono} that wraps a lazily-supplied {@link CompletableFuture} on subscription,
* emitting the value produced by the future and optionally cancelling the future if the Mono gets cancelled
* (if {@code suppressCancel == false}).
*
* <p>
* <img class="marble" src="doc-files/marbles/fromFutureSupplier.svg" alt="">
* <p>
*
* @param futureSupplier The {@link Supplier} of a {@link CompletableFuture} that will produce a value
* (or a null to complete immediately). This allows lazy triggering of future-based APIs.
* @param suppressCancel {@code true} to prevent cancellation of the future when the Mono is cancelled,
* {@code false} otherwise (the default)
* @param <T> type of the expected value
* @return A {@link Mono}.
* @see #fromCompletionStage(Supplier) fromCompletionStage for a generalization
*/
public static <T> Mono<T> fromFuture(Supplier<? extends CompletableFuture<? extends T>> futureSupplier, boolean suppressCancel) {
return defer(() -> onAssembly(new MonoCompletionStage<>(futureSupplier.get(), suppressCancel)));
}
/**
* Create a {@link Mono} that completes empty once the provided {@link Runnable} has
* been executed.
*
* <p>
* <img class="marble" src="doc-files/marbles/fromRunnable.svg" alt="">
* <p>
* @param runnable {@link Runnable} that will be executed before emitting the completion signal
*
* @param <T> The generic type of the upstream, which is preserved by this operator
* @return A {@link Mono}.
*/
public static <T> Mono<T> fromRunnable(Runnable runnable) {
return onAssembly(new MonoRunnable<>(runnable));
}
/**
* Create a {@link Mono}, producing its value using the provided {@link Supplier}. If
* the Supplier resolves to {@code null}, the resulting Mono completes empty.
*
* <p>
* <img class="marble" src="doc-files/marbles/fromSupplier.svg" alt="">
* <p>
* @param supplier {@link Supplier} that will produce the value
* @param <T> type of the expected value
*
* @return A {@link Mono}.
*/
public static <T> Mono<T> fromSupplier(Supplier<? extends T> supplier) {
return onAssembly(new MonoSupplier<>(supplier));
}
/**
* Create a new {@link Mono} that ignores elements from the source (dropping them),
* but completes when the source completes.
*
* <p>
* <img class="marble" src="doc-files/marbles/ignoreElementsForMono.svg" alt="">
* <p>
*
* <p><strong>Discard Support:</strong> This operator discards the element from the source.
*
* @param source the {@link Publisher} to ignore
* @param <T> the source type of the ignored data
*
* @return a new completable {@link Mono}.
*/
public static <T> Mono<T> ignoreElements(Publisher<T> source) {
return onAssembly(new MonoIgnorePublisher<>(source));
}
/**
* Create a new {@link Mono} that emits the specified item, which is captured at
* instantiation time.
*
* <p>
* <img class="marble" src="doc-files/marbles/just.svg" alt="">
* <p>
* @param data the only item to onNext
* @param <T> the type of the produced item
*
* @return a {@link Mono}.
*/
public static <T> Mono<T> just(T data) {
return onAssembly(new MonoJust<>(data));
}
/**
* Create a new {@link Mono} that emits the specified item if {@link Optional#isPresent()} otherwise only emits
* onComplete.
*
* <p>
* <img class="marble" src="doc-files/marbles/justOrEmpty.svg" alt="">
* <p>
* @param data the {@link Optional} item to onNext or onComplete if not present
* @param <T> the type of the produced item
*
* @return a {@link Mono}.
*/
public static <T> Mono<T> justOrEmpty(@Nullable Optional<? extends T> data) {
return data != null && data.isPresent() ? just(data.get()) : empty();
}
/**
* Create a new {@link Mono} that emits the specified item if non null otherwise only emits
* onComplete.
*
* <p>
* <img class="marble" src="doc-files/marbles/justOrEmpty.svg" alt="">
* <p>
* @param data the item to onNext or onComplete if null
* @param <T> the type of the produced item
*
* @return a {@link Mono}.
*/
public static <T> Mono<T> justOrEmpty(@Nullable T data) {
return data != null ? just(data) : empty();
}
/**
* Return a {@link Mono} that will never signal any data, error or completion signal,
* essentially running indefinitely.
* <p>
* <img class="marble" src="doc-files/marbles/never.svg" alt="">
* <p>
* @param <T> the {@link Subscriber} type target
*
* @return a never completing {@link Mono}
*/
public static <T> Mono<T> never() {
return MonoNever.instance();
}
/**
* Returns a Mono that emits a Boolean value that indicates whether two Publisher sequences are the
* same by comparing the items emitted by each Publisher pairwise.
* <p>
* <img class="marble" src="doc-files/marbles/sequenceEqual.svg" alt="">
*
* @param source1 the first Publisher to compare
* @param source2 the second Publisher to compare
* @param <T> the type of items emitted by each Publisher
* @return a Mono that emits a Boolean value that indicates whether the two sequences are the same
*/
public static <T> Mono<Boolean> sequenceEqual(Publisher<? extends T> source1, Publisher<? extends T> source2) {
return sequenceEqual(source1, source2, equalsBiPredicate(), Queues.SMALL_BUFFER_SIZE);
}
/**
* Returns a Mono that emits a Boolean value that indicates whether two Publisher sequences are the
* same by comparing the items emitted by each Publisher pairwise based on the results of a specified
* equality function.
* <p>
* <img class="marble" src="doc-files/marbles/sequenceEqual.svg" alt="">
*
* @param source1 the first Publisher to compare
* @param source2 the second Publisher to compare
* @param isEqual a function used to compare items emitted by each Publisher
* @param <T> the type of items emitted by each Publisher
* @return a Mono that emits a Boolean value that indicates whether the two Publisher two sequences
* are the same according to the specified function
*/
public static <T> Mono<Boolean> sequenceEqual(Publisher<? extends T> source1, Publisher<? extends T> source2,
BiPredicate<? super T, ? super T> isEqual) {
return sequenceEqual(source1, source2, isEqual, Queues.SMALL_BUFFER_SIZE);
}
/**
* Returns a Mono that emits a Boolean value that indicates whether two Publisher sequences are the
* same by comparing the items emitted by each Publisher pairwise based on the results of a specified
* equality function.
* <p>
* <img class="marble" src="doc-files/marbles/sequenceEqual.svg" alt="">
*
* @param source1 the first Publisher to compare
* @param source2 the second Publisher to compare
* @param isEqual a function used to compare items emitted by each Publisher
* @param prefetch the number of items to prefetch from the first and second source Publisher
* @param <T> the type of items emitted by each Publisher
* @return a Mono that emits a Boolean value that indicates whether the two Publisher two sequences
* are the same according to the specified function
*/
public static <T> Mono<Boolean> sequenceEqual(Publisher<? extends T> source1,
Publisher<? extends T> source2,
BiPredicate<? super T, ? super T> isEqual, int prefetch) {
return onAssembly(new MonoSequenceEqual<>(source1, source2, isEqual, prefetch));
}
/**
* Uses a resource, generated by a supplier for each individual Subscriber, while streaming the value from a
* Mono derived from the same resource and makes sure the resource is released if the
* sequence terminates or the Subscriber cancels.
* <p>
* <ul>
* <li>For eager cleanup, unlike in {@link Flux#using(Callable, Function, Consumer, boolean) Flux},
* in the case of a valued {@link Mono} the cleanup happens just before passing the value to downstream.
* In all cases, exceptions raised by the eager cleanup {@link Consumer} may override the terminal event,
* discarding the element if the derived {@link Mono} was valued.</li>
* <li>Non-eager cleanup will drop any exception.</li>
* </ul>
* <p>
* <img class="marble" src="doc-files/marbles/usingForMono.svg" alt="">
*
* @param resourceSupplier a {@link Callable} that is called on subscribe to create the resource
* @param sourceSupplier a {@link Mono} factory to create the Mono depending on the created resource
* @param resourceCleanup invoked on completion to clean-up the resource
* @param eager set to true to clean before any signal (including onNext) is passed downstream
* @param <T> emitted type
* @param <D> resource type
*
* @return new {@link Mono}
*/
public static <T, D> Mono<T> using(Callable<? extends D> resourceSupplier,
Function<? super D, ? extends Mono<? extends T>> sourceSupplier,
Consumer<? super D> resourceCleanup,
boolean eager) {
return onAssembly(new MonoUsing<>(resourceSupplier, sourceSupplier,
resourceCleanup, eager));
}
/**
* Uses a resource, generated by a supplier for each individual Subscriber, while streaming the value from a
* Mono derived from the same resource and makes sure the resource is released if the
* sequence terminates or the Subscriber cancels.
* <p>
* Unlike in {@link Flux#using(Callable, Function, Consumer) Flux}, in the case of a valued {@link Mono} the cleanup
* happens just before passing the value to downstream. In all cases, exceptions raised by the cleanup
* {@link Consumer} may override the terminal event, discarding the element if the derived {@link Mono} was valued.
* <p>
* <img class="marble" src="doc-files/marbles/usingForMono.svg" alt="">
*
* @param resourceSupplier a {@link Callable} that is called on subscribe to create the resource
* @param sourceSupplier a {@link Mono} factory to create the Mono depending on the created resource
* @param resourceCleanup invoked on completion to clean-up the resource
* @param <T> emitted type
* @param <D> resource type
*
* @return new {@link Mono}
*/
public static <T, D> Mono<T> using(Callable<? extends D> resourceSupplier,
Function<? super D, ? extends Mono<? extends T>> sourceSupplier,
Consumer<? super D> resourceCleanup) {
return using(resourceSupplier, sourceSupplier, resourceCleanup, true);
}
/**
* Uses a resource, generated by a {@link Publisher} for each individual {@link Subscriber},
* to derive a {@link Mono}. Note that all steps of the operator chain that would need the
* resource to be in an open stable state need to be described inside the {@code resourceClosure}
* {@link Function}.
* <p>
* Unlike in {@link Flux#usingWhen(Publisher, Function, Function) the Flux counterpart}, ALL signals are deferred
* until the {@link Mono} terminates and the relevant {@link Function} generates and invokes a "cleanup"
* {@link Publisher}. This is because a failure in the cleanup Publisher
* must result in a lone {@code onError} signal in the downstream {@link Mono} (any potential value in the
* derived {@link Mono} is discarded). Here are the various scenarios that can play out:
* <ul>
* <li>empty Mono, asyncCleanup ends with {@code onComplete()}: downstream receives {@code onComplete()}</li>
* <li>empty Mono, asyncCleanup ends with {@code onError(t)}: downstream receives {@code onError(t)}</li>
* <li>valued Mono, asyncCleanup ends with {@code onComplete()}: downstream receives {@code onNext(value),onComplete()}</li>
* <li>valued Mono, asyncCleanup ends with {@code onError(t)}: downstream receives {@code onError(t)}, {@code value} is discarded</li>
* <li>error(e) Mono, asyncCleanup ends with {@code onComplete()}: downstream receives {@code onError(e)}</li>
* <li>error(e) Mono, asyncCleanup ends with {@code onError(t)}: downstream receives {@code onError(t)}, t suppressing e</li>
* </ul>
* <p>
* <img class="marble" src="doc-files/marbles/usingWhenSuccessForMono.svg" alt="">
* <p>
* Note that if the resource supplying {@link Publisher} emits more than one resource, the
* subsequent resources are dropped ({@link Operators#onNextDropped(Object, Context)}). If
* the publisher errors AFTER having emitted one resource, the error is also silently dropped
* ({@link Operators#onErrorDropped(Throwable, Context)}).
* An empty completion or error without at least one onNext signal (no resource supplied)
* triggers a short-circuit of the main sequence with the same terminal signal
* (no cleanup is invoked).
*
* <p><strong>Discard Support:</strong> This operator discards any source element if the {@code asyncCleanup} handler fails.
*
* @param resourceSupplier a {@link Publisher} that "generates" the resource,
* subscribed for each subscription to the main sequence
* @param resourceClosure a factory to derive a {@link Mono} from the supplied resource
* @param asyncCleanup an asynchronous resource cleanup invoked when the resource
* closure terminates (with onComplete, onError or cancel)
* @param <T> the type of elements emitted by the resource closure, and thus the main sequence
* @param <D> the type of the resource object
*
* @return a new {@link Mono} built around a "transactional" resource, with deferred emission until the
* asynchronous cleanup sequence completes
*/
public static <T, D> Mono<T> usingWhen(Publisher<D> resourceSupplier,
Function<? super D, ? extends Mono<? extends T>> resourceClosure,
Function<? super D, ? extends Publisher<?>> asyncCleanup) {
return usingWhen(resourceSupplier, resourceClosure, asyncCleanup,
(res, error) -> asyncCleanup.apply(res),
asyncCleanup);
}
/**
* Uses a resource, generated by a {@link Publisher} for each individual {@link Subscriber},
* to derive a {@link Mono}.Note that all steps of the operator chain that would need the
* resource to be in an open stable state need to be described inside the {@code resourceClosure}
* {@link Function}.
* <p>
* Unlike in {@link Flux#usingWhen(Publisher, Function, Function, BiFunction, Function) the Flux counterpart},
* ALL signals are deferred until the {@link Mono} terminates and the relevant {@link Function}
* generates and invokes a "cleanup" {@link Publisher}. This is because a failure in the cleanup Publisher
* must result in a lone {@code onError} signal in the downstream {@link Mono} (any potential value in the
* derived {@link Mono} is discarded). Here are the various scenarios that can play out:
* <ul>
* <li>empty Mono, asyncComplete ends with {@code onComplete()}: downstream receives {@code onComplete()}</li>
* <li>empty Mono, asyncComplete ends with {@code onError(t)}: downstream receives {@code onError(t)}</li>
* <li>valued Mono, asyncComplete ends with {@code onComplete()}: downstream receives {@code onNext(value),onComplete()}</li>
* <li>valued Mono, asyncComplete ends with {@code onError(t)}: downstream receives {@code onError(t)}, {@code value} is discarded</li>
* <li>error(e) Mono, errorComplete ends with {@code onComplete()}: downstream receives {@code onError(e)}</li>
* <li>error(e) Mono, errorComplete ends with {@code onError(t)}: downstream receives {@code onError(t)}, t suppressing e</li>
* </ul>
* <p>
* <img class="marble" src="doc-files/marbles/usingWhenSuccessForMono.svg" alt="">
* <p>
* Individual cleanups can also be associated with mono cancellation and
* error terminations:
* <p>
* <img class="marble" src="doc-files/marbles/usingWhenFailureForMono.svg" alt="">
* <p>
* Note that if the resource supplying {@link Publisher} emits more than one resource, the
* subsequent resources are dropped ({@link Operators#onNextDropped(Object, Context)}). If
* the publisher errors AFTER having emitted one resource, the error is also silently dropped
* ({@link Operators#onErrorDropped(Throwable, Context)}).
* An empty completion or error without at least one onNext signal (no resource supplied)
* triggers a short-circuit of the main sequence with the same terminal signal
* (no cleanup is invoked).
*
* <p><strong>Discard Support:</strong> This operator discards the element if the {@code asyncComplete} handler fails.
*
* @param resourceSupplier a {@link Publisher} that "generates" the resource,
* subscribed for each subscription to the main sequence
* @param resourceClosure a factory to derive a {@link Mono} from the supplied resource
* @param asyncComplete an asynchronous resource cleanup invoked if the resource closure terminates with onComplete
* @param asyncError an asynchronous resource cleanup invoked if the resource closure terminates with onError.
* The terminating error is provided to the {@link BiFunction}
* @param asyncCancel an asynchronous resource cleanup invoked if the resource closure is cancelled.
* When {@code null}, the {@code asyncComplete} path is used instead.
* @param <T> the type of elements emitted by the resource closure, and thus the main sequence
* @param <D> the type of the resource object
*
* @return a new {@link Mono} built around a "transactional" resource, with several
* termination path triggering asynchronous cleanup sequences