user1955934
user1955934

Reputation: 3505

WebFlux How to Chain Queries In Functional Non Blocking Way

I am new to functional paradigm, wondering how to go about doing some querying before creating a new object?

@Override
public Mono<Order> create(CreateOrderRequest specs) {

    //itemRepository.findAll(specs.getItemCodes()) //returns Flux<Item>


    final Order newOrder = new Order(items);
    return orderRepository.insert(newOrder)
            .switchIfEmpty(Mono.error(new ResponseStatusException(HttpStatus.BAD_REQUEST, "Failed to create order")));
}

How do I chain the commented code in a non blocking way? The query returns Flux<Item> while Order constructor requires a List<Item>

Upvotes: 0

Views: 1064

Answers (1)

Dimitri Mestdagh
Dimitri Mestdagh

Reputation: 44745

You can use the collectList() method, which will change your Flux<Item> into a Mono<List<Item>>.

After that, you can use the map() method to convert your List<Item> into an Order object, and the flatMap() method to get the saved result.

For example:

return itemRepository
    .findAll(specs.getItemCodes())
    .collectList()
    .map(Order::new)
    .flatMap(orderRepository::insert)
    .switchIfEmpty(Mono.error(new ResponseStatusException(HttpStatus.BAD_REQUEST, "Failed to create order")));

Upvotes: 2

Related Questions