Search code examples
javareactive-programmingspring-webclient

How to get value out of mono


I'm trying to extract a String out out Mono.

Mono method:

public Mono<String> getVal() {
    return webClient.get()
        .uri("/service") 
        .retrieve()
        .bodyToMono(String.class);
}

Calling getVal():

String val = getVal().block();

I tried using block() but it returns the following error:

java.lang.IllegalStateException: block()/blockFirst()/blockLast() are blocking, 
which is not supported in thread reactor-http-nio-3

I suppose I would have to use a non-blocking method like subscribe() which I'm not to sure how to.


Solution

  • If you are using reactive programming, try to avoid blocking calls and use already existing features.

    public Mono<String> getVal() {
        return webClient.get()
            .uri("/service") 
            .retrieve()
            .bodyToMono(String.class)
            .map(str ->  {
              // You have your string unwrapped here
              return str;
            });
    }