问题
Could someone help me to understand the difference between Mono.defer(), Mono.create() and Mono.just()? How to use it properly?
回答1:
Mono.just(value)
is the most primitive - once you have a value you can wrap it into a Mono and subscribers down the line will get it.
Mono.defer(monoSupplier)
lets you provide the whole expression that supplies the resulting Mono
instance. The evaluation of this expression is deferred until somebody subscribes. Inside of this expression you can additionally use control structures like Mono.error(throwable)
to signal an error condition (you cannot do this with Mono.just
).
Mono.create(monoSinkConsumer)
is the most advanced method that gives you the full control over the emitted values. Instead of the need to return Mono
instance from the callback (as in Mono.defer
), you get control over the MonoSink<T>
that lets you emit values through MonoSink.success()
, MonoSink.success(value)
, MonoSink.error(throwable)
methods.
Reactor documentation contains a few good examples of possible Mono.create
use cases: link to doc.
The general advice is to use the least powerful abstraction to do the job: Mono.just -> Mono.defer -> Mono.create
.
来源:https://stackoverflow.com/questions/56115447/mono-defer-vs-mono-create-vs-mono-just