Reactive Programming with Reactor 3

Reactor
532.6K views

Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

Mono

Description

A Mono<T> is a Reactive Streams Publisher, also augmented with a lot of operators that can be used to generate, transform, orchestrate Mono sequences.

It is a specialization of Flux that can emit at most 1 <T> element: a Mono is either valued (complete with element), empty (complete without element) or failed (error).

A Mono<Void> can be used in cases where only the completion signal is interesting (the Reactive Streams equivalent of a Runnable task completing).

Like for Flux, the operators can be used to define an asynchronous pipeline which will be materialized anew for each Subscription.

Note that some API that change the sequence's cardinality will return a Flux (and vice-versa, APIs that reduce the cardinality to 1 in a Flux return a Mono).

See the javadoc here.

Marble diagram representation of a Mono

Mono in action:

Mono.firstWithValue(
        Mono.just(1).map(integer -> "foo" + integer),
        Mono.delay(Duration.ofMillis(100)).thenReturn("bar")
    )
    .subscribe(System.out::println);

Practice

As for the Flux let's return a empty Mono using the static factory.

static <T> Mono<T> empty()
// Create a Mono that completes without emitting any item.
Empty Mono

Now, we will try to create a Mono which never emits anything. Unlike empty(), it won't even emit an onComplete event.

No Emission

Like Flux, you can create a Mono from an available (unique) value.

Create a Mono from an item

And exactly as we did for the flux, we can propagate exceptions.

Create a Mono that emits an IllegalStateException
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content