javaasynchronouscompletable-futurecompletion-stage

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 i.e. 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.


Solution

  • 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");
      }