2015-06-07 40 views
1

我使用的服務(從庫,我不能改變它)有3種方法:嵌套的異步任務(在Java中使用CompletionStage)

CompletionStage<AData> getAData(int id); 
CompletionStage<BData> getBData(int id); 
CompletionStage<Path> computePath(int id); 

我的目的,我應該得到威剛和BDATA,然後在此基礎上嘗試值計算一些Path,如果我不能做到這一點 - 使用服務呼叫

所以我的代碼現在看起來像:

CompletionStage<Path> getPath(int id) { 
     service.getAData(id).thenCombine(service.getBdata(id)), (a, b) -> 
     { 
      Path result = computePathLocaly(a, b); 
      return result != null ? 
          result : 
          service.computePath(id).toCompletableFuture().join(); 
     } 
} 

都做工精細,但toCompletableFuture().join()看起來很糟糕。 包裝resultCompletionStage並返回CompletionStage<CompletionStage<Path>> - 甚至更糟......

我相信的,它是可以更優雅地做了,但我不能認識到如何...請幫助。

回答

2

您可以用computePathLocally呼叫

CompletionStage<Path> getPath(int id) { 
     service.getAData(id).thenCombine(service.getBdata(id)), (a, b) -> 
      return computePathLocally(a, b); 
     ).thenCompose((result) -> 
      return result != null ? 
        CompletableFuture.completedFuture(result) : 
        service.computePath(id); 
     ) 
} 
+0

所有這麼簡單...謝謝撰寫service.computePath(id)的來電! – Puh