This series of articles index the "Response Spring's word Wizard"
Previously summary Reactor Operators
This section is from the Reactor 3 reference document I translated--how to select the operator. Because some friends open Github.io network speed is relatively slow or not to go, posted out for easy access to everyone.
If an operator is exclusive to Flux
or Mono
, it will be prefixed.
Common operators do not have a prefix. If a specific use case involves a combination of multiple operators, this is presented in the form of a method call,
Starts with a dot (.) and places the parameter in parentheses, such as: .methodCall(parameter)
.
1) Create a new sequence, it ...
- Send
T
out one that I have already had:just
- ... Based on one
Optional<T>
:Mono#justOrEmpty(Optional<T>)
- ... Based on a possible
null
T:Mono#justOrEmpty(T)
- Emit one
T
, and still be returned by the just
method
- ... But "lazy" created by: Use
Mono#fromSupplier
or defer
packagingjust
- Emit
T
A lot of these elements I can explicitly enumerate out:Flux#just(T...)
- Based on the iterative data structure:
- An array:
Flux#fromArray
- A collection or iterable:
Flux#fromIterable
- A range of integers:
Flux#range
- One for
Stream
each subscription:Flux#fromStream(Supplier<Stream>)
- A source given based on a parameter value:
- One
Supplier<T>
:Mono#fromSupplier
- A task:
Mono#fromCallable
,Mono#fromRunnable
- One
CompletableFuture<T>
:Mono#fromFuture
- Direct completion:
empty
- Generate error immediately:
error
- ... But the "lazy" way to generate
Throwable
:error(Supplier<Throwable>)
- Do not do anything:
never
- When you subscribe, you decide:
defer
- To rely on a recyclable resource:
using
- To generate events programmatically (can use state):
- Synchronous and individual:
Flux#generate
- Asynchronously (also synchronous), emit as many elements as possible at a time:
Flux#create
( Mono#create
also asynchronous, only one can be sent)
2) Conversion of the sequence
I want to convert a sequence:
- 1 to 1 conversions (such as a string into its length):
map
- ... Type conversions:
cast
- ... In order to get the ordinal of each element:
Flux#index
- 1 to n conversions (such as strings into a string of characters):
flatMap
+ Use a factory method
- 1 to N conversion customizable conversion method and/or status:
handle
- Performs an asynchronous operation on each element, such as an HTTP request to a URL:
flatMap
+ a method of an asynchronous return type Publisher
- ... Omit some data: Returns a flatMap in lambda based on conditions
Mono.empty()
- ... Keep the original sequence order:
Flux#flatMapSequential
(asynchronous tasks for each element are executed immediately, but the results are sorted in the order of the original sequence)
- ... When the asynchronous task of the Mono element returns a sequence of multiple elements:
Mono#flatMapMany
I want to add some data elements to an existing sequence:
- Add at the beginning:
Flux#startWith(T...)
- Added at the end:
Flux#concatWith(T...)
I want to convert it into a Flux
collection (which is all for Flux
a moment)
- Convert to List:
collectList
,collectSortedList
- Convert to Map:
collectMap
,collectMultiMap
- Conversion to a custom collection:
collect
- Count:
count
- Reduce algorithm (reduce the previous element's reduce result with the current element value as input to execute the method, such as sum)
reduce
- ... The results of each reduce are immediately emitted:
scan
- Translates to a Boolean value:
- Evaluates to true for all elements:
all
- Evaluates to at least one element as true:
any
- Determines whether the sequence has elements (not NULL):
hasElements
- Determine if there is a matching element in the sequence:
hasElement
I want to merge publishers ...
- Connected by order:
Flux#concat
or.concatWith(other)
- ... Even if there is an error, it will wait for all publishers connections to complete:
Flux#concatDelayError
- ... Connect in order of subscription (here the merge can still be understood as a sequence of connections):
Flux#mergeSequential
- Merges in the order in which the elements are emitted (regardless of which sequence, the elements are first to first merged):
Flux#merge
/.mergeWith(other)
- ... The element type will vary:
Flux#zip
/Flux#zipWith
- To combine elements:
- 2 Monos consisting of 1
Tuple2
:Mono#zipWith
- n Monos elements are sent out to form a Tuple:
Mono#zip
- "Take action" when the termination signal appears:
- When Mono terminates, it is converted to one
Mono<Void>
:Mono#and
- Returns when n Mono is terminated
Mono<Void>
:Mono#when
- Returns a type that holds the combined data for multiple sequences that are merged:
- When each sequence emits an element:
Flux#zip
- When any sequence emits an element:
Flux#combineLatest
- Only the first element of each sequence is taken:,,,
Flux#first
Mono#first
mono.or<br/>(otherMono).or(thirdMono)
' flux.or (Otherflux). or (Thirdflux)
- triggered by a sequence (similar to
flatMap
, but "hate"):switchMap
- Triggered by the start of each new sequence (also "hate" style):
switchOnNext
I want to repeat a sequence:repeat
- ... But repeat at a certain interval:
Flux.interval(duration).flatMap(tick -> myExistingPublisher)
I have an empty sequence, but ...
- I want a default value instead:
defaultIfEmpty
- I want a default sequence instead:
switchIfEmpty
I have a sequence, but I'm not interested in the element values of the sequence:ignoreElements
- ... And I want to use it
Mono
to indicate that the sequence has ended:then
- ... And I want to wait for another task to finish after the sequence ends:
thenEmpty
- ... And I want to return one after the end of the sequence
Mono
:Mono#then(mono)
- ... And I want to return a value after the sequence ends:
Mono#thenReturn(T)
- ... And I want to return one after the end of the sequence
Flux
:thenMany
I have a Mono but I want to delay the completion ...
- ... Complete when 1 or n other publishers are emitted (or ended):
Mono#delayUntilOther
- ... Use a functional formula to define how to get "other publisher":
Mono#delayUntil(Function)
- I want to extend each element based on the rules of a recursive generation sequence, and then merge the emitted into a sequence:
- ... Breadth First:
expand(Function)
- ... Depth First:
expandDeep(Function)
3) "Peep" (read-only) sequence
4) Filter Sequence
5) Error Handling
I want to create an error sequence: error
...
- ... To replace a completed
Flux
:.concat(Flux.error(e))
- ... To replace a completed
Mono
:.then(Mono.error(e))
- ... If the element timed out does not emit:
timeout
- ... "lazy" create:
error(Supplier<Throwable>)
I want an expression like Try/catch:
- Throw exception:
error
- Catching Exceptions:
- The default value is then returned:
onErrorReturn
- Then return one
Flux
or Mono
:onErrorResume
- After the package exception, throw:
.onErrorMap(t -> new RuntimeException(t))
- Finally code block:
doFinally
- Try-with-resources notation after Java 7:
using
Factory method
I want to recover from the error ...
- Returns a default:
- Values of:
onErrorReturn
Publisher
: Flux#onErrorResume
andMono#onErrorResume
- Retry:
retry
- ... By one used to accompany the Flux trigger:
retryWhen
- I want to handle the back pressure error (send "MAX" request upstream, if the request is less downstream, apply the policy) ...
- Thrown
IllegalStateException
:Flux#onBackpressureError
- Discard policy:
Flux#onBackpressureDrop
- ... But the last element is not discarded:
Flux#onBackpressureLatest
- Cache policy (limited or unlimited):
Flux#onBackpressureBuffer
- ... Apply a given policy when limited cache space is full:
Flux#onBackpressureBuffer
with policyBufferOverflowStrategy
6) Time-based operations
I want to convert the element to a time-information Tuple2<Long, T>
...
- Start at subscription time:
elapsed
- Record time stamp:
timestamp
If the delay between elements is too long, the sequence is aborted:timeout
Emit elements in a fixed period:Flux#interval
Emitted after a given delay 0
: static Mono.delay
.
- I want to introduce a delay:
- For each of the elements:
Mono#delayElement
,Flux#delayElements
- Deferred subscription:
delaySubscription
7) SplitFlux
8) Back to the synchronized world
With 2:reactor 3 selection of the appropriate operator--response spring's DAO spell device