Java 8 Completable Futures allOf different data types

后端 未结 4 1628
你的背包
你的背包 2020-12-14 09:52

I have 3 CompletableFutures all 3 returning different data types.

I am looking to create a result object that is a composition of the result returned by all the 3 fu

4条回答
  •  攒了一身酷
    2020-12-14 10:29

    I was going down a similar route to what @Holger was doing in his answer, but wrapping the Service Calls in an Optional, which leads to cleaner code in the thenApplyAsync stage

    CompletableFuture> classAFuture
        = CompletableFuture.supplyAsync(() -> Optional.ofNullable(service.getClassA())));
    
    CompletableFuture> classBFuture
        = CompletableFuture.supplyAsync(() -> Optional.ofNullable(service.getClassB()));
    
    CompletableFuture> classCFuture
        = CompletableFuture.supplyAsync(() -> Optional.ofNullable(service.getClassC()));
    
    return CompletableFuture.allOf(classAFuture, classBFuture, classCFuture)
         .thenApplyAsync(dummy -> {
            ClassD resultClass = new ClassD();
    
            classAFuture.join().ifPresent(resultClass::setClassA)
            classBFuture.join().ifPresent(resultClass::setClassB)
            classCFuture.join().ifPresent(resultClass::setClassC)
    
            return resultClass;
         });
    

提交回复
热议问题