Search code examples
reactive-programmingproject-reactorreactive-streams

Mono vs Flux in Reactive Stream


As per the documentation:

Flux is a stream which can emit 0..N elements:

Flux<String> fl = Flux.just("a", "b", "c");

Mono is a stream of 0..1 elements:

Mono<String> mn = Mono.just("hello");

And as both are the implementations of the Publisher interface in the reactive stream.

Can't we use only Flux in most of the cases as it also can emit 0..1, thus satisfying the conditions of a Mono?

Or there are some specific conditions when only Mono needs to be used and Flux can not handle the operations? Please suggest.


Solution

  • In many cases, you are doing some computation or calling a service and you expect exactly one result (or maybe zero or one result), and not a collection that contains possibly multiple results. In such cases, it's more convenient to have a Mono.

    Compare it to "regular" Java: you would not use List as the return type of any method that can return zero or one result. You would use Optional instead, which makes it immediately clear that you do not expect more than one result.