Search code examples
javaspring-webfluxspring-webclient

How to get object from WebClient bodyToMono or toEntity in a Non-Blocking way


I am new to Spring WebClient. I have the following method calling an endpoint using WebClient and I need to return ResponseEntity from this method. I know that I can call block(), but is there anyway I can do it in a non-blocking way? Even if I can return Mono, the calling method will still need to unwrap it and get the ResponseEntity, how does the calling method do, call the block?

public ResponseEntity getData() {

    Mono<ResponseEntity<String>> entityMono = webClient.post()
                                                       .uri(url)
                                                       .body(BodyInserters.fromValue(aString))
                                                       .retrieve()
                                                       .toEntity(String.class);

     // what do I need to do here so that I can return ResponseEntity non-blocking

}

Solution

  • if you want to return a ResponseEntity there is no other way, you need to block.

    Think of it this way, you do a request, you need to wait for the response until we can construct a ResponseEntity because we need the returned data until we can build it.

    If you are writing a fully non-blocking application, this is bad, since in the middle of everything you are basically yelling STOP, and the entire application freezes until it gets the response and then continues.

    The other option is to return a Mono<ResponseEntity> which is more like a promise. You are basically saying that "when i get the answer back, i will promise that there will be a ResponseEntity, i just dont know when so you will have to do with the Mono for now`

    Then after that you can extract, transform, using functions like, map, flatMap, zip, etc. etc but as long as you always return a Mono because remember, we dont have the value, we are basically just building a pipeline of what we want our application to do when we actually have the value.

    i suggest you go through the Reactor Documentation to understand what problem reactive programming solves, and then how to get started with it as it is way too much to explain in a simple answer on stack overflow.