The definition of
Mono.defer
is described in detail in
stack overflow comment
. If we use Mono.defer, we can operate Mono.defer's wrapped code at the time of execution, not at the time of declaration. So I understood that It would be necessary to subscribe several times in one context.
However, even in a situation that was not the case, I met
Mono.defer
and couldn't understand at first.
Let's see below code. If we don't use
Mono.defer
, we have to declare separately Mono for switchIfEmpty. If there is a value in the cache,
this.apiClient.getDataNoById(id).doOnSuccess(TODO)
method is always executed even if switchIfEmpty is not executed.
// without using Mono.deferpublicMono<Data>requiredById(Stringid){Mono<Long>alternate=this.apiClient.getDataNoById(id).doOnSuccess(TODO);returnMono.justOrEmpty(cache.getData(id)).switchIfEmpty(alternate).flatMap(this::requiredOne)publicMono<Data>requiredById(Stringid){returnMono.justOrEmpty(cache.getData(id)).switchIfEmpty(Mono.defer(()->this.apiClient.getDataNoById(id).doOnSuccess(TODO))).flatMap(this::requiredOne)Enter fullscreen modeExit fullscreen mode
However, the getDataNoById method returns the Mono type and has not subscribed yet. Therefore, the actual webClient call does not occur. So I didn't understand why Mono.defer was necessary in there.
As a result, If switchIfEmpty supports the lambda expression, It doesn't have to use Mono.defer. But java doesn't support it, so they used Mono.defer.
cf) spring.web.reactive.dispatcherHandler also uses Mono.defer. Even though it is simply creating an Exception object and wrapping it with Mono.error, using Mono.defer seems to have written it as a way to create a clean code.