With 2:reactor 3 selection of the appropriate operator--response spring's DAO spell device

Source: Internet
Author: User
Tags emit iterable throw exception throwable

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 conditionsMono.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 -&gt; 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

    • No more changes to the sequence, I think:

      • Get notified or do something:
      • emit element: doonnext
      • sequence Complete: flux#dooncomplete , mono#doonsuccess
      • terminated for error: doonerror
      • Cancel: Dooncancel
      • at subscription time: doonsubscribe
      • on request: doonrequest
      • completion or error termination: doonterminate (mono method may contain results)
        • But after terminating the signal downstream : doafterterminate< /code>
      • All types of signals ( Signal ): flux#dooneach
      • all end conditions (complete, wrong Error, canceling cancel): dofinally
      • logging: log
    • I want to know all the events:
      • Each event is represented as a single object:
      • Execute callback: dooneach
      • Convert each element to single Object: materialize
        • ... Converting back to element: dematerialize
      • to a single line of logs: log

4) Filter Sequence

  • I want to filter a sequence

    • Based on a given judgment condition:filter
    • ... To make a judgment asynchronously:filterWhen
    • Objects of the specified type only:ofType
    • Ignore all elements:ignoreElements
    • Go weight:
    • For the entire sequence:Flux#distinct
    • Remove elements that are continuously repeated:Flux#distinctUntilChanged
  • I want only part of the sequence:

    • As long as N elements:
    • Count from the first element of the sequence:Flux#take(long)
      • ... Take the elements emitted over time:Flux#take(Duration)
      • ... Just take the first element and Mono return it in:Flux#next()
      • ... Use request(N) instead of cancel:Flux#limitRequest(long)
    • Countdown from the last element of the sequence:Flux#takeLast
    • Until a certain condition (inclusive) is met: Flux#takeUntil (based on the judging criteria), Flux#takeUntilOther (based on the comparison to publisher)
    • Until a condition is met (not included):Flux#takeWhile
    • Only up to 1 elements are taken:
    • Given ordinal:Flux#elementAt
    • Last one:.takeLast(1)
      • ... If the sequence is empty, an error signal is emitted:Flux#last()
      • ... Returns the default value if the sequence is empty:Flux#last(T)
    • Skip over some elements:
    • Skips from the first element of a sequence:Flux#skip(long)
      • ... Skipping elements emitted over a period of time:Flux#skip(Duration)
    • Skip the last n elements:Flux#skipLast
    • Until a certain condition (inclusive) is met: Flux#skipUntil (based on the judging criteria), Flux#skipUntilOther (based on the comparison to publisher)
    • Until a condition is met (not included):Flux#skipWhile
    • Sampling:
    • Given sample period:Flux#sample(Duration)
      • Take the first element in the sampling period instead of the last one:sampleFirst
    • Based on another publisher:Flux#sample(Publisher)
    • Based on publisher "Timeout": Flux#sampleTimeout (each element triggers a publisher If this element is emitted by publisher overrides that are not triggered by the next element)
  • I only want one element (if more than one returns an error) ...
    • If the sequence is empty, an error signal is emitted:Flux#single()
    • If the sequence is empty, a default value is emitted:Flux#single(T)
    • Returns an empty sequence if the sequence is empty:Flux#singleOrEmpty

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&lt;Throwable&gt;)
  • 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 -&gt; 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&lt;Long, T&gt; ...

      • 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

  • I want to put a flux&lt; t&gt; Split into a flux&lt; flux&lt; t&gt;&gt; :

    • is bounded by number: window (int)
    • ... When overlapping or discarding occurs: window (int, int)
    • Time-bound: window (Duration)
    • ... Overlap or Discard occurs: window (Duration, Duration)
    • in number or time bounds: windowtimeout (int, Duration) The
    • is based on the criteria for determining the element: windowuntil
    • ... The element that triggers the judging condition is divided into the next wave (the cutbefore variable): . Windowuntil (predicate, true)
    • ... Satisfies the condition of the element in a wave until the element that does not satisfy the condition emits the next wave: windowwhile (the element that does not meet the criteria is discarded)
    • splits the sequence through each of the other Publisher's OnNext signals: Code>window (Publisher) , windowwhen
  • I want to put a flux&lt; t&gt; The elements are split into collections ...

    • splits a single List :
    • to a number of bounds: buffer (int)
      • ... Overlap or discard occurs: buffer (int, int)
    • Time-bound: buffer (Duration)
      • . When overlapping or discarding occurs: buffer (Duration, Duration)
    • in number or time: buffertimeout (int, Duration)
    • based on the judging criteria for the element: bufferuntil (predicate)
      • ... The element that triggers the judging condition is divided into the next buffer: . Bufferuntil (predicate, true)
      • ... The element that satisfies the condition is in a buffer until the element that does not satisfy the condition begins to emit the next buffer: bufferwhile (predicate)
    • through another Publisher Each of the OnNext signals to split the sequence: buffer (Publisher) , bufferwhen
    • Split to the specified type of collection: Buffer (int, supplier&lt; c&gt;)
  • I want to Flux&lt;T&gt; group elements with common characteristics into sub-Flux: groupBy(Function&lt;T,K&gt;) (note that the return value is Flux&lt;GroupedFlux&lt;K, T&gt;&gt; that each GroupedFlux has the same key value, which K can be key() obtained by means of a method).

8) Back to the synchronized world

    • I have one Flux&lt;T&gt; , I think:

      • Block before getting the first element:Flux#blockFirst
      • ... And give the time-out period:Flux#blockFirst(Duration)
      • Blocks before getting the last element (returns NULL if the sequence is empty):Flux#blockLast
      • ... And give the time-out period:Flux#blockLast(Duration)
      • To convert synchronously to Iterable&lt;T&gt; :Flux#toIterable
      • To convert to Java 8 synchronously Stream&lt;T&gt; :Flux#toStream
    • I have one Mono&lt;T&gt; , I think:
      • Block before getting the element:Mono#block
      • ... And give the time-out period:Mono#block(Duration)
      • Convert to CompletableFuture&lt;T&gt; :Mono#toFuture

With 2:reactor 3 selection of the appropriate operator--response spring's DAO spell device

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.