The flatMap operator works in a similar way to the map, but works asynchronously. This means that it should return an instance that can return a value in the future, such as Flux or Mono. The following example code shows how it can be used:
Flux.fromArray(arrayOf(1, 2, 3))
.flatMap { Mono.just(it).delayElement(Duration.ofSeconds(1)) }
.subscribe { println(it) }
The output of this example looks as follows:
1
2
3
Mono is similar to Flux, but it can emit one or zero elements. In this example, we use the delayElement function, which is why each element is received by a subscriber with a one-second delay.
The following diagram shows how it works:
This shows that each flatMap operator passes each value to the downstream asynchronously, with a one-second delay.