简体   繁体   中英

Java - sync call inside async thenCompose

Consider below code as I am not able to find better words to ask the question:

CompletionStage<Manager> callingAsyncFunction(int developerId) {
    return getManagerIdByDeveloperId(developerId)
           .thenCompose(id ->
             getManagerById(id, mandatoryComputationToGetManager(id)))
}

mandatoryComputationToGetManager() returns a CompletionStage

Now the doubt which I have is :

I wanted to call mandatoryComputationToGetManager() and after its computation I want getManagerById(...) to be called.

I know there can be one way ie calling thenCompose() first to do mandatoryComputationToGetManager() and then do another thenCompose() on previous result for getManagerById() . But I wanted to figure out if there is a way without piping one thenCompose() o/p to another by which I can hold until mandatoryComputationToGetManager() result is ready.

As far as I understand, in the above code getManagerById() will get called even if the result is not yet ready from mandatoryComputationToGetManager() , which I want to wait for so that once mandatoryComputationToGetManager() give the result getManagerById() should get computed asynchronously.

Ideally, we should pipe one thenCompose o/p to another, but there is a way by which we can achieve what you are trying to do.

  CompletionStage<String> callingAsyncFunction(int developerId) {
    return getManagerIdByDeveloperId(developerId)
        .thenCompose(id -> getManagerById(id, mandatoryComputationToGetManager()));
  }

  private CompletionStage<String> getManagerById(
      Integer id, CompletionStage<String> stringCompletionStage) {
    return stringCompletionStage.thenApply(__ -> "test");
  }

  private CompletionStage<String> mandatoryComputationToGetManager() {
    return CompletableFuture.completedFuture("test");
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM