首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >WebFlux和空值

WebFlux和空值
EN

Stack Overflow用户
提问于 2022-10-12 12:06:10
回答 1查看 37关注 0票数 1

我有一个简单的dto,其中的字段可以是空的。

代码语言:javascript
复制
public ResponseDto{
...
  @Nullable
  public List<ListDto> getListDto() {
    return this.listDto;
  }
...
}

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

代码语言:javascript
复制
  @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);
  }

我的一个决定-重写地图

代码语言:javascript
复制
.map(responseDto -> Objects.requireNonNull(responseDto .getListDto()))

关于如何正确实现此检查,还有其他选项吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-10-13 08:54:44

在反应性上下文中,null应该是空的。不能从映射器中返回null,至少在反应堆/WebFlux中不能返回null。

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

WebFlux中的惯用方法是完全过滤掉不需要的值,然后用defaultIfEmpty()switchIfEmpty()对空的Mono作出反应。

代码语言:javascript
复制
 @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());
  }
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74041549

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档