Spring 5.0 Projects
上QQ阅读APP看书,第一时间看更新

Reactor types

Project Reactor is built with two core types based on the number of elements they process. They are considered as main building blocks to create a Reactive System using Reactor. They are Flux and Mono. They both implement the Publisher<T> interface and conform to Reactive Streams specification, and  are furnished with reactive-pull and back-pressure facility. They also have several other useful methods. Let's explore the details as follows: 

  • Flux: It can be considered the equivalent of RxJava's Observable and can emit zero or more items, ending successfully or with an error signal. In short, it represents asynchronous event streams having zero or more elements. 
  • Mono: It can emit, at most, one element at a time. It is equivalent of the Single and Maybe Observable type from the RxJava side. A Mono type can be used for one-to-one request-response model implementation; for example, a task wish to send a completion signal can use a Mono type reactor.

The clear difference between the number of elements a reactor type can handle provides useful semantics and makes it an easy decision to choose which reactor type. If the model is sort of fire and forget then choose the Mono type. If execution is dealing with multiple data items or elements in the stream, then the Flux type is more appropriate.

Additionally, various operators play a vital role in deciding the type of reactor. For example, calling asingle() method on a Flux<T> type will return Mono<T>, while concatenating multiple entities of type Mono<T> together with concatWith() will result in the Flux<T> type. The reactor type can influence which operators we can use with it. For example, some operators are applicable to either one of  Flux or Mono while others can be used for both of them.