Mono vs Flux in Reactive Stream
Asked Answered
P

5

77

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.

Prince answered 27/12, 2017 at 7:57 Comment(0)
G
76

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.

Gudrunguelderrose answered 31/12, 2017 at 7:57 Comment(0)
S
38

Flux is equivalent to RxJava Observable is capable of emitting
- zero or more item (streams of many elements)
- and then OPTIONALLY , completing OR failing

Mono can only emit one item at the most (streams one element)

Relations:

  • If you concatente two Monos you will get a Flux
  • You can call single() on Flux to return a Mono
Skinhead answered 24/3, 2018 at 17:8 Comment(0)
P
7

From the docs here

This distinction carries a bit of semantic information into the type, indicating the rough cardinality of the asynchronous processing. For instance, an HTTP request produces only one response, so there is not much sense in doing a count operation. Expressing the result of such an HTTP call as a Mono thus makes more sense than expressing it as a Flux, as it offers only operators that are relevant to a context of zero items or one item.

Peale answered 27/12, 2017 at 8:51 Comment(0)
A
1

Simply as the Mono is used for handling zero or one result, while the Flux is used to handle zero to many results, possibly even infinite results. And both two in common behave in a purely asynchronous and fully non-blocking.

Autrey answered 22/1, 2021 at 12:27 Comment(0)
P
0

I think it is good practice to use Mono in cases where we know we can only get one result. In this way, we make it known to other developers working on the same thing that the result can be 0 or 1.

We are following that approach on all our projects.

Here is one good tutorial on Reactive Streams and the uses of Mono and Flux -> Reactive programming in Java.

Paleethnology answered 24/1, 2022 at 12:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.