我有一个简单的dto,其中的字段可以是空的。
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(responseDto -> Objects.requireNonNull(responseDto .getListDto()))关于如何正确实现此检查,还有其他选项吗?
发布于 2022-10-13 08:54:44
在反应性上下文中,null应该是空的。不能从映射器中返回null,至少在反应堆/WebFlux中不能返回null。
如果您需要进一步处理所有值,即使它们是null,我建议使用可选的。
WebFlux中的惯用方法是完全过滤掉不需要的值,然后用defaultIfEmpty()或switchIfEmpty()对空的Mono作出反应。
@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());
}https://stackoverflow.com/questions/74041549
复制相似问题