Compare to the flatMap() method in the Java Stream object or the flatMap() method in the Optional object in Java, we can manipulate the Stream or Optional objects of the simpler objects, the flatMap() method of the Mono object or the Flux object in the Project Reactor with the parameter as a Function, used to execute the function with the items that the Publisher (Mono/Flux) object emit. These items will be processed asynchronously, that is, do not wait for the execution of the function for one item to finish before executing the function for the next item. The result after executing the function will be emitted by a new Publisher, to continue performing other operations in the event stream:
The blue and yellow items in the image above after being processed, the results will be emitted by a Publisher and if we have many operations to do with these items, there will be many Publishers that need to use to emit the results. These operations will be performed asynchronously.
For example, I have a simple Flux object as follows:
1 |
Flux<String> flux = Flux.just("Khanh", "Quan"); |
Using the flatMap() method, we can convert the data emitted from the Flux object above from String to Integer and this result is emitted by another Mono object acting as a Publisher. The example is as follows:
1 2 3 4 5 6 |
flux.flatMap(s -> Mono.just(s.length())) .map(value -> { System.out.println(value); return value; }) .subscribe(); |
The result after converting from String to Integer will be passed to the map() method to print the console value as you can see!
Result:
Mono’s flatMap() method is similar.