Home > Software design >  How to get field value from Mono<Class>?
How to get field value from Mono<Class>?

Time:11-16

I have 2 methods.

`Mono<Order> order = orderService.getById(UUID id);`

AND

Mono<Truck> truck = vehicleService.getByTruckId(UUID truckId);

I get the TruckId value from the first request. Look at Order class

Order {

private UUID id;
private String name;
private UUID truckId;

}

How can I pass this truckId value to vehicleService.getByTruckId(UUID truckId); without blocking?

CodePudding user response:

If you only care about the Truck

    Mono<Truck> truckMono = order.flatMap(o -> getByTruckId(o.truckId));

If you care about the aggregation of order and it's truck

    Mono<Order> orderMono = getById(UUID.randomUUID());
    Mono<Truck> truckMono = orderMono.flatMap(o -> getByTruckId(o.truckId));
    Mono<Result> resultMono = Mono.zip(orderMono, truckMono)
            .flatMap(m -> Mono.just(new Result(m.getT1(), m.getT2())));

Result Class

class Result {
    public Result(Order order, Truck truck) {
        this.order = order;
        this.truck = truck;
    }

    Order order;
    Truck truck;
}
  • Related