我有一个简单的 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/