spring-webflux - WebFlux 和 null 值

标签 spring-webflux nullable

我有一个简单的 dto,其中一个字段可以为 null

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

如何正确实现检查消失消除警告

  @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);
  }

我的决定之一 - 重写 map

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

还有其他选项可以帮助您正确实现此检查吗?

最佳答案

null 在响应式上下文中应该为空。您不能从映射器返回 null,至少在 Reactor/WebFlux 中不能。

如果您需要进一步处理所有值,即使它们为空,我建议使用可选值。

WebFlux 中惯用的方法是完全过滤掉不需要的值,并使用 defaultIfEmpty()switchIfEmpty() 对空 Mono 作出 react :

 @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());
  }

关于spring-webflux - WebFlux 和 null 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74041549/

相关文章:

project-reactor - 在计划任务中使用 Flux

WCF - 将空元素转换为可为空的 native 类型

c# - 如何指定 "collection of nullable types"的约束?

c# - 绑定(bind)到值类型的通用类型参数 - 使它们可以为空

c# - 如何将 nullable int 转换为 nullable short?

spring - 更改 WebFilter 中 ServerWebExchange 响应的正文

spring-boot - Spring Webflux 和 @Cacheable - 缓存 Mono/Flux 类型结果的正确方法

java - Spring Webflux 响应式(Reactive) Mongo 批量操作 (Java)

c# - 可空变量类型 - .value 成员

file - spring webflux Flux<DataBuffer> 转换为 InputStream