hydradon
hydradon

Reputation: 1426

Zip 2 different Mono in Spring Webfux

I have the below function

public Mono<CarAndShip> getCarAndShip(Long id) {
    Mono<Car> carMono = carService.getCar(id).subscribeOn(Schedulers.elastic());
    Mono<Ship> shipMono = shipService.getShip(id).subscribeOn(Schedulers.elastic());

    return Mono.zip(carMono, shipMono)
        .flatMap(zipMono -> {
            return new CarAndShip(zipMono.getT1(), zipMono.getT2());
        });

IntelliJ complains at the return statement that:

Required type: Mono <CarAndShip> 
Provided: Mono <Object> no
instance(s) of type variable(s) R exist so that CarAndShip conforms to Mono<? extends R>

How do I type cast to the required CarAndShip return type?

Upvotes: 0

Views: 2338

Answers (2)

Puce
Puce

Reputation: 38132

Required type: Mono Provided: Mono no instance(s) of type variable(s) R exist so that CarAndShip conforms to Mono<? extends R>

As the exception says: you're not providing a Mono.

So either use map instead of flatMap:

return Mono.zip(carMono, shipMono)
    .map(zipMono -> new CarAndShip(zipMono.getT1(), zipMono.getT2()));

or provide a Mono (probably not the best way here):

return Mono.zip(carMono, shipMono)
    .flatMap(zipMono -> Mono.just(new CarAndShip(zipMono.getT1(), zipMono.getT2())));

Upvotes: 4

Michael McFadyen
Michael McFadyen

Reputation: 2987

In this example you should be using map() instead of flatMap() as you are not returning a Mono.

Upvotes: 2

Related Questions