DEV Community

yangbongsoo
yangbongsoo

Posted on

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)