Search code examples
javafunctional-programmingreactive-programming

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


I have a method which accepts Mono as a param. All I want is to get the actual String from it. Googled but didn't find answer except calling block() over Mono object but it will make a blocking call so want to avoid using block(). Please suggest other way if possible. The reason why I need this String is because inside this method I need to call another method say print() with the actual String value. I understand this is easy but I am new to reactive programming.

Code:

public String getValue(Mono<String> monoString) {
    // How to get actual String from param monoString
    // and call print(String) method
}

public void print(String str) {
    System.out.println(str);
}

Solution

  • Finally what worked for me is calling flatMap method like below:

    public void getValue(Mono<String> monoString)
    {
       monoString.flatMap(this::print);
    }