1. Overview

In our Intro to Project Reactor, we learned about Mono, which is a publisher of an instance of type T.

In this quick tutorial, we’ll demonstrate both a blocking and non-blocking way to extract T from the Monoblock and subscribe.

2. Blocking Way

In general, Mono completes successfully by emitting an element at some point in time.

Let’s start with an example publisher Mono:

Mono<String> blockingHelloWorld() {
    return Mono.just("Hello world!");
}

String result = blockingHelloWorld().block();
assertEquals("Hello world!", result);

Here, we’re blocking the execution as long as the publisher doesn’t emit the value. However, it can take any amount of time to finish.

To get more control, we’ll set an explicit duration:

String result = blockingHelloWorld().block(Duration.of(1000, ChronoUnit.MILLIS));
assertEquals(expected, result);

If the publisher doesn’t emit a value within the set duration, a RuntimeException is thrown.

Additionally, Mono could be empty and the block() method above would return null. In that case, we could make use of block**Optional:

Optional<String> result = Mono.<String>empty().blockOptional();
assertEquals(Optional.empty(), result);

In general, blocking contradicts the principles of reactive programming. It’s highly discouraged to block the execution in reactive applications.

So now let’s see how to get the value in a non-blocking way.

3. Non-Blocking Way

First of all, we should subscribe in a non-blocking way using the subscribe() method. We’ll also specify the consumer of the final value:

blockingHelloWorld()
  .subscribe(result -> assertEquals(expected, result));

Here, even if it takes some time to produce the value, the execution immediately continues without blocking on the subscribe() call.

In some cases, we’ll want to consume the value in intermediate steps. Therefore, we can use an operator to add behavior:

blockingHelloWorld()
  .doOnNext(result -> assertEquals(expected, result))
  .subscribe();

4. Conclusion

In this brief article, we explored two ways of consuming a value produced by Mono.

As always, the code example can be found over on GitHub.