英文:
Reactor flatmap inside a flatmap
问题
在传统的非响应式编程中,我的代码将如下所示:
public OrderEstimationsResult getEstimations(ObjectId productId, int quantity, float longitude, float latitude, ShipmentMethod shipmentMethod) {
Product product = productService.getById(productId);
ShippingEstimationResult estimation = shippingService.getEstimations(product.getWeight(), product.getLocation(), new Location(longitude, latitude), new Date(), ShipmentMethod.FAST);
float price = productService.calculatePrice(product, quantity);
return new OrderEstimationsResult(price, estimation.getEstimatedCost(), new Date());
}
在响应式编程中,我使用了 flatMap 内部的 flatMap 来实现这一点。
public Mono<OrderEstimationsResult> getEstimations(ObjectId productId, int quantity, float longitude, float latitude, ShipmentMethod shipmentMethod) {
return productService
.getById(productId)
.flatMap(product -> shippingService
.getEstimations(product.getWeight(), product.getLocation(), new Location(longitude, latitude), new Date(), ShipmentMethod.FAST)
.flatMap(estimation -> {
float price = productService.calculatePrice(product, quantity);
return Mono.just(new OrderEstimationsResult(price, estimation.getEstimatedCost(), new Date()));
})
);
}
请问是否有人可以告诉我我是否在使用正确/最佳的方法?
英文:
I have faced a problem while transforming two streams to single-stream while the second one is depended on the first stream.
In traditional non-reactive programming my code would be written as following.
public OrderEstimationsResult getEstimations(ObjectId productId, int quantity, float longitude, float latitude, ShipmentMethod shipmentMethod) {
Product product = productService.getById(productId);
ShippingEstimationResult estimation = shippingService.getEstimations(product.getWeight(), product.getLocation(), new Location(longitude, latitude), new Date(), ShipmentMethod.FAST);
float price = productService.calculatePrice(product, quantity);
return new OrderEstimationsResult(price, estimation.getEstimatedCost(), new Date());
}
I managed to do this using flatmap inside a flatmap in reactive programming.
public Mono<OrderEstimationsResult> getEstimations(ObjectId productId, int quantity, float longitude, float latitude, ShipmentMethod shipmentMethod) {
return productService
.getById(productId)
.flatMap(product -> shippingService
.getEstimations(product.getWeight(), product.getLocation(), new Location(longitude, latitude), new Date(), ShipmentMethod.FAST)
.flatMap(estimation -> {
float price = productService.calculatePrice(product, quantity);
return Mono.just(new OrderEstimationsResult(price, estimation.getEstimatedCost(), new Date()));
})
);
}
Could anyone please tell whether I'm using the correct/best approach?
专注分享java语言的经验与见解,让所有开发者获益!
评论