Aliaksei
Aliaksei

Reputation: 1457

WebFlux and null value

I have simple dto, with a field that can be null

public ResponseDto{
...
  @Nullable
  public List<ListDto> getListDto() {
    return this.listDto;
  }
...
}

How to correctly implement the check that disappeared remove the warning

  @NotNull
  public Flux<ListDto> getApplicationList(String applicationSubsidiesId) {
    return Mono.fromCallable(() -> mapper.toRq(applicationSubsidiesId))
        .subscribeOn(Schedulers.boundedElastic())
        .flatMap(subsidiesClient::getResponseById)
        .filter(responseDto -> Objects.nonNull(responseDto.getListDto()))
        .map(ResponseDto::getListDto) <- Return null or something nullable from a lambda in transformation method 
        .flatMapMany(Flux::fromIterable);
  }

One of my decisions - rewrite map

.map(responseDto -> Objects.requireNonNull(responseDto .getListDto()))

Are there any other options on how to correctly implement this check?

Upvotes: 2

Views: 4404

Answers (1)

Erunafailaro
Erunafailaro

Reputation: 1959

null should be Empty in a reactive context. You cannot return null from a mapper, at least not in Reactor/WebFlux.

If you need to further process all values, even if they are null, I would suggest using an optional.

The idiomatic approach in WebFlux would be to filter out unwanted values completely and the react to an empty Mono with defaultIfEmpty() or switchIfEmpty():

 @NotNull
  public Flux<ListDto> getApplicationList(String applicationSubsidiesId) {

    final var defaultResponseDto = new ResponseDto();

    return Mono.fromCallable(() -> mapper.toRq(applicationSubsidiesId))
        .subscribeOn(Schedulers.boundedElastic())
        .flatMap(subsidiesClient::getResponseById)
        .filter(responseDto -> Objects.nonNull(responseDto.getListDto()))

        // filter may cause an empty flux, in which case the next line
        // will not be executed.
        .flatMapMany(Flux::fromIterable)

        // in case of an empty flux, this line will kick in:
        .defaultIfEmpty(Flux.fromIterable(defaultResponseDto.getListDto()));

        // as an alternative, you can call for a fallback:
        // .switchIfEmpty(getAnotherFluxFromSomewhereElse());
  }

Upvotes: 2

Related Questions