Quantcast
Channel: Baeldung
Viewing all articles
Browse latest Browse all 4535

How to Get String From Mono in Reactive Java

$
0
0

1. Overview

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

In this quick tutorial, we'll show both a blocking and a non-blocking way to extract 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<String>:

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, let's 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 will return null. We can, instead, make use of blockOptional in that case:

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. Also, we'll 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 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 short article, we have explored two ways of consuming a value produced by Mono<String>.

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


Viewing all articles
Browse latest Browse all 4535

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>