Extract Data from Mono in Java

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!";
    });
  }
}
Output: Data from Mono: 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);

  }
}
Output: data
 
With subscribe(), the current thread will not be blocked waiting for the Publisher to emit data.

See more about subscribing to a Mono in Java here.

That’s it!

Leave a Reply

Your email address will not be published. Required fields are marked *