I am creating a Flux of Product and a Mono Category object that needs to be applied to the Products because all they all all to be grouped into the same category. I am attempting to add the category to each Product like this.
Flux<Product> products = productRepository.findAllById(productCodes);
Mono<Category> category = categoryRepository.findById(productCodes.get(0));
The category for all these products should be set as:
//If these were a list of products i.e List<Product> productList and Category was
//not a Mono I would set them like this:
productList.forEach( product -> product.setCategory(category));
Since the respective repositories return Mono and Flux respectively, I am unsure how to do that use the reactive framework as I am very new to it. Can someone please show me how to achieve this using reactive?
Actually, there are many ways to implement this.
Here is an example where you apply function with flatMap()
to every element of your product flux. This function uses your category Mono
to to set the category to the product.
productsFlux.flatMap(product -> categoryMono.map(category -> {
product.setCategory(category);
return product;
}));
Or vice versa using flatMapMany()
on you category Mono:
categoryMono.flatMapMany(category -> productsFlux.map(product -> {
product.setCategory(category);
return product;
}));
Or you can turn your category Mono
into hot-never-ending flux with cache and do Flux.zip()
on your products flux and category flux, like this: (I would prefer this option since it is better to ensure that db call for category called only once)
Flux<String> categoryHotFlux = categoryMono.cache().repeat();
Flux.zip(productsFlux, categoryHotFlux)
.map(tuple -> {
Product product = tuple.getT1();
Category category = tuple.getT2();
product.setCategory(category);
return product;
});