How to get String from Mono<String> in reactive java

How to get String from Mono<String> in reactive java

In reactive programming with Java, particularly with the Project Reactor library, you can extract a String value from a Mono<String> using various methods provided by Reactor. Here's how you can do it:

import reactor.core.publisher.Mono; public class MonoExample { public static void main(String[] args) { // Create a Mono<String> with a value Mono<String> mono = Mono.just("Hello, Reactive Java!"); // Method 1: Using block() String result1 = mono.block(); System.out.println("Method 1: " + result1); // Method 2: Using subscribe() mono.subscribe(result2 -> { System.out.println("Method 2: " + result2); }); // Method 3: Using map() (if you need to transform the value) Mono<String> transformedMono = mono.map(value -> "Transformed: " + value); transformedMono.subscribe(result3 -> { System.out.println("Method 3: " + result3); }); } } 

In this example, we create a Mono<String> called mono with a string value. Then, we demonstrate three different methods to extract the String value from the Mono:

  1. Using block():

    • The block() method waits for the Mono to emit a value and returns that value. However, you should be cautious when using block() because it can block the calling thread, which is generally discouraged in reactive programming.
  2. Using subscribe():

    • The subscribe() method allows you to provide a callback to process the emitted value when it becomes available. This is the recommended way to handle values in a non-blocking manner.
  3. Using map():

    • If you need to transform the value before extracting it, you can use the map() operator to apply a function to the emitted value. In this example, we transform the string to prepend "Transformed: " to it.

Remember that in reactive programming, it's generally best to work with Mono, Flux, or other reactive types using non-blocking operations like subscribe, map, filter, and others, to maintain the asynchronous and non-blocking nature of reactive programming.


More Tags

xdebug e-commerce shared-hosting xcode-ui-testing jira memory-leak-detector cljsrn lxml react-leaflet multimarkdown

More Java Questions

More Biochemistry Calculators

More Chemical reactions Calculators

More Various Measurements Units Calculators

More Other animals Calculators