Felix
Felix

Reputation: 147

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 (e.g. 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.

Upvotes: 0

Views: 738

Answers (1)

123
123

Reputation: 11216

You can use flatMapMany

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

Upvotes: 1

Related Questions