Spring webflux 如何使用Mono<;布尔值>;作为调用第二个方法的条件
在检查另一个服务的状况后,我正在尝试呼叫一个服务 通过迭代的方式,我可以做到这一点Spring webflux 如何使用Mono<;布尔值>;作为调用第二个方法的条件,spring-webflux,reactor,Spring Webflux,Reactor,在检查另一个服务的状况后,我正在尝试呼叫一个服务 通过迭代的方式,我可以做到这一点 if (productService.isProductNotExcluded(product)){ List<Properties> properties = propertiesService.getProductDetailProperties(product) ... } if(productService.isProductNotExcluded(产品)){ 列表属性=proper
if (productService.isProductNotExcluded(product)){
List<Properties> properties = propertiesService.getProductDetailProperties(product)
...
}
if(productService.isProductNotExcluded(产品)){
列表属性=propertiesService.getProductDetailProperties(产品)
...
}
但是,由于isProductExcluded正在返回Mono
,我正在使用这种方法,这看起来非常奇怪
Flux<Properties> properties = productService.isProductNotExcluded(productId)
.filter(notExcluded -> notExcluded)
.map(ok-> propertiesService.getProductDetailProperties(product))
...
Flux properties=productService.isProductNotExcluded(productId)
.filter(notExcluded->notExcluded)
.map(确定->属性服务.getProductDetailProperties(产品))
...
解决这种情况的正确方法是什么?您所做的并不奇怪,如果可以避免的话,我个人不会在反应函数
Mono中返回布尔值,但这并没有错,有时您没有选择余地
为了清楚起见,我个人会在地图上写一个if-else语句。我将更改函数的名称,并重写isNot
部分
Flux<Properties> properties = productService.isExcluded(productId)
.flatMap(isExcluded -> {
if(!isExcluded)
return propertiesService.getProductDetailProperties(product);
else
return mono.empty();
});
Flux properties=productService.isExcluded(productId)
.flatMap(不包括->{
如果(!IsExclude)
返回propertiesService.getProductDetailProperties(产品);
其他的
返回mono.empty();
});
这是一个观点和编码品味的问题,但我发现这更具可读性,因为您可以直接阅读代码并理解它。但这是个人喜好。对于返回单声道的谓词,您也可以使用以发布者为谓词的过滤器。大概是这样的:
Flux<Properties> properties = Mono.just(productId)
.filterWhen(prodId -> productService.isProductNotExcluded(prodId))
.map(validProductId -> propertiesService.getProductDetailProperties(validProductId));
Flux properties=Mono.just(productId)
.filterWhen(prodId->productService.isProductNotExcluded(prodId))
.map(validProductId->propertiesService.getProductDetailProperties(validProductId));
您可以在映射
函数中做一个if-else语句,这并不奇怪。如果您不喜欢它,那么您可以使用Thomas Andolf解决方案,我相信它应该是一个平面图