Link to home
Start Free TrialLog in
Avatar of Rohit Bajaj
Rohit BajajFlag for India

asked on

Using completionStage Properly

Hi,
There is following code -
 
     
   public CompletionStage<Void> addEmail(Long userID, String email) {

      CompletableFuture<GetMappingResponsePayload> getMappingResponsePayloadCompletionStage =
              (CompletableFuture<GetMappingResponsePayload>) addressResolver.getEmailMapping(email);

    return addressResolver.addEmailMapping(email, userID)
        .thenCompose(__ -> emailsDao.upsertEmail(userID, email, true));

Open in new window

I want to fetch the object GetMappingResponsePayload from above.
The getEmailMapping function is a synchronous call so when the code gets executed the result will be there.
To give the context there is a Boolean attribute inside GetMappingResponsePayload and based on that
i want to return an exceptionallyCompletedFuture in case the value is false.
otherwise the next return statement is executed.
How do i achieve this neatly

Thanks
ASKER CERTIFIED SOLUTION
Avatar of girionis
girionis
Flag of Greece image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Rohit Bajaj

ASKER

There is one more way that i figured out. I wanted to avoid catching Exception. Because the future would be complete and get method throws exception so here is what i did... Please advice on the code below :
 final Boolean[] isEmailPresentForDifferentJID = {false};
    addressResolver.getEmailMapping(email).
        thenAccept((getMappingResponsePayload) -> {
          JID jidFromEmail = getMappingResponsePayload.getJID();
          JID jidFromUserID = UserService.getNodeJID(userID);
          if (jidFromEmail != null && !jidFromUserID.equals(jidFromEmail))
            isEmailPresentForDifferentJID[0] = true;
        });
    return isEmailPresentForDifferentJID[0];

Open in new window


This may seem somewhat different from what i posted.. But the essential thing here is instead of get i used thenAccept and assigned the boolean from inside of the lambda expression..And now i can directly use this boolean.
Please suggest any pros and cons of this approach
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial