Reputation: 382
Is flatMap on Flux always sequential? I know that It is not sequential when then function used in flatMap return flux. project-reactor flatMap
But if the function used in flatMap returns mono, would it be always sequential?
Say I have a function that takes an object and returns only Mono.
fun aFunction(foo: Int): Mono<Int> {
return (foo + 1).toMono()
}
then
Flux.just(1,2,3,4)
.flatMap{ aFunction(it) }
always return 2,3,4,5?
Upvotes: 4
Views: 6861
Reputation: 4642
No, a flatMap
is not sequential. A flatMap
subscribes eagerly to the inner streams. Here is a summary of how it works:
Since these inner subscriptions happen in parallel, there is no guarantee on which inner stream will emit an onComplete
first. Therefore, there is no ordering guarantee.
concatMap
on the other hand gives ordering guarantee (in the exact order as it receives events from upstream). This is because it subscribes to the next stream only after the previous stream has emitted an onComplete
.
Here's an article I wrote on flatMap
a while back:
https://medium.com/swlh/understanding-reactors-flatmap-operator-a6a7e62d3e95
Note: It's highly likely that you'll see 2,3,4,5 in the output. This happens as your calls are synchronous. But there is no guarantee, and you should never rely on flatMap
for any sort of ordering requirements.
Upvotes: 13