Search code examples
java-8futurecompletable-future

CompletableFuture - How to Use Local Variable in a Future Result


I am using CompletableFuture in a java application. In the following code:

testMethod(List<String> ids)  {

    for(String id : ids) {
        CompletableFuture<Boolean> resultOne = AynchOne(id);
        CompletableFuture<Boolean> resultTwo = AynchTwo(id);
    
CompletableFuture<Boolean> resultThree = resultOne.thenCombine(resultTwo, (Boolean a, Boolean b) -> {
     Boolean andedResult = a && b;
     return andedResult;
    });

resultThree.thenApply(andedResult -> {
     if(andedResult.booleanValue() == true) {
         forwardSucccess(**id**);
      }
      return null;
    });
}

}


void forwardSucccess(String id) {
    // do stuff in the future
}

, the "id" is local to testMethod(), and thus I don't believe in the future context (at thenApply()). I have it in the code snippet where you see forwardSuccess(id), but since its not part of a futures, its probably null or undefined at the time "forwardSuccess(id)" is executed.

Is there a way to introduce the "id" into the futures somehow?

Thanks for any ideas.


Solution

  • My original coding was close to being correct. The value of the variable "id" is correct at the future time because its value in context of the for-loop is automatically forwarded by the magic of CompletableFuture. If this was obvious to others, it was not to me (which is why I posted !).

    Other than that realization, I simplified the logic some (based on the useful comment by Mr Holger above).

    testMethod(List<String> ids)  {
    
        for(String id : ids) {
            CompletableFuture<Boolean> resultOne = AynchOne(id);
            CompletableFuture<Boolean> resultTwo = AynchTwo(id);
    
            CompletableFuture<Boolean> resultThree = resultOne.thenCombine(resultTwo, (a,b) -> a && b); 
    
        resultThree.thenApply(andedResult -> {
            if(andedResult == true) {
                forwardSucccess(id);
            }
            return null;
        });
    }
    
    
    void forwardSucccess(String id) {
        // do stuff in the future
    }