Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 466
KayV Avatar asked Dec 27 '17 07:12

KayV


People also ask

What is mono and flux in reactive programming?

A Flux object represents a reactive sequence of 0.. N items, while a Mono object represents a single-value-or-empty (0..1) result. This distinction carries a bit of semantic information into the type, indicating the rough cardinality of the asynchronous processing.

What is mono in reactive?

A Reactive Streams Publisher with basic rx operators that emits at most one item via the onNext signal then terminates with an onComplete signal (successful Mono, with or without value), or only emits a single onError signal (failed Mono). Most Mono implementations are expected to immediately call Subscriber.

What is mono and flux in WebFlux?

Spring WebFlux internally uses Project Reactor and its publisher implementations, Flux and Mono. Mono — A publisher that can emit 0 or 1 element. Flux — A publisher that can emit 0.. N elements.

What is flux in reactive programming?

Mono and Flux are both reactive streams. They differ in what they express. A Mono is a stream of 0 to 1 element, whereas a Flux is a stream of 0 to N elements.


2 Answers

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.

like image 80
Jesper Avatar answered Sep 18 '22 14:09

Jesper


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
like image 41
MagGGG Avatar answered Sep 18 '22 14:09

MagGGG