DEV Community

yangbongsoo
yangbongsoo

Posted on

1

Java Mono.defer usecase

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.defer
public Mono<Data> requiredById(String id) {
  Mono<Long> alternate = this.apiClient.getDataNoById(id).doOnSuccess(TODO);

  return Mono.justOrEmpty(cache.getData(id))
    .switchIfEmpty(alternate)
    .flatMap(this::requiredOne)
    ...
}
Enter fullscreen mode Exit fullscreen mode

If we use Mono.defer instead, we can make Mono.defer's wrapped code operate when switchIfEmpty runs.

// use Mono.defer
public Mono<Data> requiredById(String id) {

  return Mono.justOrEmpty(cache.getData(id))
    .switchIfEmpty(Mono.defer(() -> this.apiClient.getDataNoById(id).doOnSuccess(TODO)))
    .flatMap(this::requiredOne)
    ...
}
Enter fullscreen mode Exit 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.

@Override
public Mono<Void> handle(ServerWebExchange exchange) {
  if (this.handlerMappings == null) {
    return createNotFoundError();
  }

  return Flux.fromIterable(this.handlerMappings)
    .concatMap(mapping -> mapping.getHandler(exchange))
    .next()
    .switchIfEmpty(createNotFoundError())
    .flatMap(handler -> invokeHandler(exchange, handler))
    .flatMap(result -> handleResult(exchange, result));
}

private <R> Mono<R> createNotFoundError() {
  return Mono.defer(() -> {
    Exception ex = new ResponseStatusException(HttpStatus.NOT_FOUND, "No matching handler");
    return Mono.error(ex);
  });
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

Great read:

Is it Time to go Back to the Monolith?

History repeats itself. Everything old is new again and I’ve been around long enough to see ideas discarded, rediscovered and return triumphantly to overtake the fad. In recent years SQL has made a tremendous comeback from the dead. We love relational databases all over again. I think the Monolith will have its space odyssey moment again. Microservices and serverless are trends pushed by the cloud vendors, designed to sell us more cloud computing resources.

Microservices make very little sense financially for most use cases. Yes, they can ramp down. But when they scale up, they pay the costs in dividends. The increased observability costs alone line the pockets of the “big cloud” vendors.

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay