Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between a Future and a Mono

In (Java) reactive programming, what is the difference between a Future<T> and a (Project Reactor) Mono<T>? Both seem to be means for accessing the result of an asynchronous computation at a time in the future when the computation is complete. Why introduce the Mono interface if Future already does the job?

like image 840
Raedwald Avatar asked Jan 17 '19 15:01

Raedwald


People also ask

What is difference between mono and flux?

Mono is more relatable to the Optional class in Java since it contains 0 or 1 value, and Flux is more relatable to List since it can have N number of values.

What is a mono stream?

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.

What is a mono in reactive programming?

Description. It is a specialization of Flux that can emit at most 1 <T> element: a Mono is either valued (complete with element), empty (complete without element) or failed (error).

How do you convert flux to Mono?

flatMap() operator We use flatMap() when the transformation returns a Flux or Mono. The flatMap() flattens the result and extracts the data from the Mono. So we should use it when we know that we will have one of the Reactive Types as the data source. That would be all regarding how to transform Flux and Mono in Java.


1 Answers

The greatest difference is that a Mono<T> can be fully lazy, whereas when you get hold of a Future<T>, the underlying processing has already started.

With a typical cold Mono, nothing happens until you subscribe() to it, which makes it possible to pass the Mono around in the application and enrich it with operators along the way, before even starting the processing.

It is also far easier to keep things asynchronous using a Mono compared to a Future (where the API tends to drive you to call the blocking get()).

Finally, compared to both Future and CompletableFuture, the composition aspect is improved in Mono with the extensive vocabulary of operators it offers.

like image 172
Simon Baslé Avatar answered Sep 18 '22 11:09

Simon Baslé