Java 8 Completable Futures allOf different data types

后端 未结 4 1616
你的背包
你的背包 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:28

    Another way to handle this if you don't want to declare as many variables is to use thenCombine or thenCombineAsync to chain your futures together.

    public CompletableFuture getResultClassD()
    {
      return CompletableFuture.supplyAsync(ClassD::new)
        .thenCombine(CompletableFuture.supplyAsync(service::getClassA), (d, a) -> {
          d.setClassA(a);
          return d;
        })
        .thenCombine(CompletableFuture.supplyAsync(service::getClassB), (d, b) -> {
          d.setClassB(b);
          return d;
        })
        .thenCombine(CompletableFuture.supplyAsync(service::getClassC), (d, c) -> {
          d.setClassC(c);
          return d;
        });
    }
    

    The getters will still be fired off asynchronously and the results executed in order. It's basically another syntax option to get the same result.

提交回复
热议问题