What is the advantage of using FlatMap over Map while transforming a webclient response?

84 Views Asked by At

I’m consuming a third-party REST API using webclient. I need to transform the response and return the result asynchronously without blocking.

My understanding is

flatMap is asynchronous and map is synchronous.

In the below code snippet, I have used flatMap in approach 1 and map in approach 2.

Question 1: Is the approach1 asynchronous?

Question 2: What is the advantage of asynchronous (flatMap over map) here? I am just fetching a field from the response and setting the field again in a different object and returning it.

@PostMapping(value = “/test”, produces = { “application/json” })
public ResponseEntity<Mono<MyResponse>> test(@RequestBody String input) {
Mono<ThirdPartyResponse> response = myutil.invokeWebClient(input);

//approach 1

final Mono<MyResponse> transformedResponse1 = response.flatMap(value -> {
    final MyResponse myResponse = new MyResponse();
    myResponse.setAccountNumber(value.getRoot().getMsgOut().getAcctNbr());
    return Mono.just(myResponse);
});

//approach 2

final Mono<MyResponse> transformedResponse2 = response.map(value -> {
    final MyResponse myResponse = new MyResponse();
    myResponse.setAccountNumber(value.getRoot().getMsgOut().getAcctNbr());
    return myResponse;
});
return ResponseEntity.status(HttpStatus.OK).body(transformedResponse1);
}
1

There are 1 best solutions below

2
SebastianK On

The main differences between map and flatmap:

  1. map() applies a one-to-one transformation to stream elements, while flatMap() does one-to-many.
  2. map() is synchronous, ensuring that all items are processed in the order that they are received. flatMap() can be asynchronous, which does not guarantee that the order of execution follows the order of invoking.

More info on Baeldung.