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);
}
The main differences between map and flatmap:
More info on Baeldung.