简体   繁体   中英

Spring Webflux Non-Blocking Dependent Resource Calls

I am using Spring Webflux and Spring Data MongoDB Reactive. In my REST Controller I am trying to get all objects of a kind (eg all bikes of a brand) from the database (MongoDB). My current implementation looks like this:

@GetMapping("/bybrand/{brandId}")
public Flux<Bike> bikesByBrand(@PathVariable(value = "brandId") String brandId) {
    return bikeRepository.findByBrand( //returns a Flux<Bike>
            brandRepository.findById(brandId) //returns a Mono<Brand>
                    .block() //returns a Brand
    );
}

To stay in the reactive pattern I want to avoid the block() call. I tried diverse combinations of map() and doOnSuccess() but didn't find the right way to do what I want to do. Examples or tutorials I found online did not cover the use case of using dependent calls to the database. How can I avoid using block() here and what would be the gold standard for accessing the database with a dependent previous call?

Another approach of mine would be the following.

brandRepository.findById(brandId)
            .doOnSuccess(brand -> bikeRepository.findByBrand(brand));

But I can't find a way to finally return the result of the lambda function (the Flux of Bike) in the superior method.

You can use flatMapMany

return brandRepository.findById(brandId).flatMapMany(bikeRepository::findByBrand)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM