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);
}
Getting a
String
from aMono<String>
without a blocking call isn't easy, it's impossible. By definition. If theString
isn't available yet (whichMono<String>
allows), you can't get it except by waiting until it comes in and that's exactly what blocking is.Instead of "getting a
String
" yousubscribe
to theMono
and theSubscriber
you pass will get theString
when it becomes available (maybe immediately). E.g.will print the value or error produced by
myMono
(type ofvalue
isString
, type oferror
isThrowable
). At https://projectreactor.io/docs/core/release/api/reactor/core/publisher/Mono.html you can see other variants ofsubscribe
too.What worked for me was the following:
monoString.subscribe(this::print);
Better
According to the doc you can do:
be aware of the blocking call
Finally what worked for me is calling flatMap method like below: