有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Zip 2在Spring Webfux中的不同Mono

我有下面的功能

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在返回声明中抱怨:

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

如何将cast类型转换为所需的CarAndShip返回类型


共 (2) 个答案

  1. # 1 楼答案

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

    例外情况是:你没有提供单声道

    所以要么使用map而不是flatMap

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

    或者提供单声道(这里可能不是最好的方式):

    return Mono.zip(carMono, shipMono)
        .flatMap(zipMono -> Mono.just(new CarAndShip(zipMono.getT1(), zipMono.getT2())));
    
  2. # 2 楼答案

    在本例中,您应该使用map()而不是flatMap(),因为您没有返回Mono