Skip to content

Instantly share code, notes, and snippets.

@Raouf25
Last active January 1, 2021 09:50
Show Gist options
  • Save Raouf25/ff7c6d37e5fd0257de12da00b491119b to your computer and use it in GitHub Desktop.
Save Raouf25/ff7c6d37e5fd0257de12da00b491119b to your computer and use it in GitHub Desktop.
The flatMap method is similar to the map method with the key difference that the supplier you provide to it should return a Mono<T> or Flux<T> . Using the map method would result in a Mono<Mono<T>> whereas using flatMap results in a Mono<T> . For example, it is useful when you have to make a network call to retrieve a data, with a java api that …
// Signature of the HttpClient.get method
Mono<JsonObject> get(String url);
// The two urls to call
String firstUserUrl = "my-api/first-user";
String userDetailsUrl = "my-api/users/details/"; // needs the id at the end
// Example with map
Mono<Mono<JsonObject>> result = HttpClient.get(firstUserUrl).
map(user -> HttpClient.get(userDetailsUrl + user.getId()));
// This results with a Mono<Mono<...>> because HttpClient.get(...)
// returns a Mono
// Same example with flatMap
Mono<JsonObject> bestResult = HttpClient.get(firstUserUrl).
flatMap(user -> HttpClient.get(userDetailsUrl + user.getId()));
// Now the result has the type we expected
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment