Mono is a Publisher from Project Reactor that can emit 0 or 1 item. There are two ways to extract data from Mono:
- Blocking
- Non-blocking
Extract data from Mono in Java – blocking way
We can use the blocking subscriber to pause the thread execution until we get the data from Mono. This way of extracting data is discouraged since we should always use the Reactive Streams in an async and non-blocking way.
We can use the block() method that subscribes to a Mono and block indefinitely until the next signal is received.
Example
import reactor.core.publisher.Mono; class ReactiveJavaTutorial { public static void main(String[] args) { String dataFromMono = getMono().block(); System.out.println("Data from Mono: " + dataFromMono); } private static Mono getMono() { return Mono.fromSupplier(() -> { try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } return "Hello!"; }); } }
Get the data from Mono in Java – non-blocking way
A non-blocking way would be via one of the overloaded subscribe() methods.
In this example, we will use the subscribe(Consumer<? super T> consumer) to get the data from Mono asynchronously.
Example
class ReactiveJavaTutorial { public static void main(String[] args) { Mono.just("data").subscribe(System.out::println); } }
See more about subscribing to a Mono in Java here.
That’s it!