concept Mono in category spring

appears as: Mono
Spring in Action, Fifth Edition

This is an excerpt from Manning's book Spring in Action, Fifth Edition.

The Mono in the example is one of Reactor’s two core types. Flux is the other. Both are implementations of Reactive Streams’ Publisher. A Flux represents a pipeline of zero, one, or many (potentially infinite) data items. A Mono is a specialized reactive type that’s optimized for when the dataset is known to have no more than one data item.

Reactive flows are often illustrated with marble diagrams. Marble diagrams, in their simplest form, depict a timeline of data as it flows through a Flux or Mono at the top, an operation in the middle, and the timeline of the resulting Flux or Mono at the bottom. Figure 10.1 shows a marble diagram template for a Flux. As you can see, as data flows through the original Flux, it’s processed through some operation, resulting in a new Flux through which the processed data flows.

Figure 10.1. Marble diagram illustrating the basic flow of a Flux

Figure 10.2 shows a similar marble diagram, but for a Mono. As you can see, the key difference is that a Mono will have either zero or one data item, or an error.

Figure 10.2. Marble diagram illustrating the basic flow of a Mono

In section 10.3, we’ll explore many operations supported by Flux and Mono, and we’ll use marble diagrams to visualize how they work.

Figure 10.19. The collect-list operation results in a Mono containing a list of all messages emitted by the incoming Flux.

Rather than produce a Flux that publishes a List, collectList() produces a Mono that publishes a List. The following test method shows how it might be used:

@Test
public void collectList() {
  Flux<String> fruitFlux = Flux.just(
      "apple", "orange", "banana", "kiwi", "strawberry");

  Mono<List<String>> fruitListMono = fruitFlux.collectList();

  StepVerifier
      .create(fruitListMono)
      .expectNext(Arrays.asList(
          "apple", "orange", "banana", "kiwi", "strawberry"))
      .verifyComplete();
}

An even more interesting way of collecting items emitted by a Flux is to collect them into a Map. As shown in figure 10.20, the collectMap() operation results in a Mono that publishes a Map that’s populated with entries whose key is calculated by a given Function.

Figure 10.20. The collect-map operation results in a Mono containing a Map of messages emitted by the incoming Flux, where the key is derived from some characteristic of the incoming messages.

Sometimes you just need to know if the entries published by a Mono or Flux match some criteria. The all() and any() operations perform such logic. Figures 10.21 and 10.22 illustrate how all() and any() work.

sitemap

Unable to load book!

The book could not be loaded.

(try again in a couple of minutes)

manning.com homepage
test yourself with a liveTest