1. Overview
In this article, we will learn to convert Mono to object java without block. To know about Mono or Flux reactive stream, refer to this article.
A Flux object represents a reactive sequence of 0..N items, whereas a Mono object represents a single value or an empty (0..1) result. As you know, Mono is an asynchronous call that executes in a non-blocking way. The following methods are available to retrieve the value from the Mono object.
The block()
method explicitly blocks the main or the caller thread until the publisher (Mono) completes. You must avoid this method as this has the potential to lock your whole reactive pipeline.
Alternatively, you can use subscribe()
call asynchronously execute the Mono
on a separate scheduler, leaving your main or caller thread to complete. Since the default scheduler uses daemon threads to execute your subscription code, the application won’t wait for it to complete before terminating.
2. Convert Mono to object java without block
You can retrieve the result from Mono in a non-blocking way by subscribing a Consumer that will consume all the sequences. The Consumer code block executes asynchronously only after Mono completes.
Disposable subscribe(Consumer<? super T> consumer)
For example, the following subscribe method prints the result of Mono to the console.
getMono() .subscribe(System.out::println);
You can use the returned Disposable instance to cancel the subscription.
Disposable disposable = getMono() .subscribe(System.out::println); disposable.dispose();
You can also subscribe for errors that can happen during Mono execution.
getMono().subscribe(result -> System.out.println(result.toUpperCase()), error -> System.out.println(error.getMessage()));
3. Chain multiple consumers
You can chain multiple consumers using doOnNext
method. Once Mono completes, the result is passed downstream to the chained consumers for further processing. Note that the doOnNext
are consumers of the result of Mono and not publishers, meaning they don’t pass (publish) any value downstream.
For example, both the doOnNext
methods and subscribe methods consume the result of Mono.
getMono().doOnNext(r -> { if (result != null) { String value = result.toUpperCase(); System.out.println(value); } }) .doOnNext(r -> { if (result != null) { String value = result.toLowerCase(); System.out.println(value); } }) .subscribe(System.out::println);
3. Conclusion
To sum up, we have learned to convert Mono to object java without block. You can get samples discussed in this article from our GitHub repository.
The solutions offered above commit the caller into a non blocking solution.
What if I wanted to start the operation non blocking but later have to block and wait? Looking for capability like a vavr Future.
Pingback: Notes – Reactor Java | William Yip's Blog