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?
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.
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.
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).
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With