简体   繁体   中英

Struggling with CompletableFuture execution

I have an issue, where I need to make several API calls in succession and return a specific object type.

I can't wrap my head around exactly how I should be utalizing CompletableFuture's to solve this issue. The return type for getSomeDetails , has to be ObjectB, but I can't return that until I've got my hands on ObjectA which has additional data.

What is a propery way to appropach this?

public CompletableFuture<ObjectB> getSomeDetails(String someIdentifier) {
  // I need to return details from ObjectB (getObjectBDetails)
  // But can only get those, after getting ObjectA, which has additional data.
}

public CompletableFuture<ObjectA> getObjectADetails(String someIdentifier) {
  return ObjectA;
}

public CompletableFuture<ObjectB> getObjectBDetails(ObjectA) {
   ObjectB = someService.get(ObjectA.someImportantProperty)
   return objectB;
}

You're mostly there: how about

import static java.util.concurrent.CompletableFuture.completedFuture;

public CompletableFuture<ObjectA> getObjectADetails(String someIdentifier) {
    return completedFuture(new ObjectA(someIdentifier));
}

public CompletableFuture<ObjectB> getObjectBDetails(ObjectA a) {
    return completedFuture(new ObjectB(a));
}

public CompletableFuture<ObjectB> getSomeDetails(String someIdentifier) {
    return getObjectADetails(someIdentifier)
        .thenCompose(this::getObjectBDetails);
}

public void run() throws Exception {
    System.out.println(getSomeDetails("request").get().toString());
}

.thenCompose tranforms a CompletableFuture -returning function to another CompletableFuture (aka "flatMap"). If .getObjectBDetails returned just an ObjectB , you'd use .thenApply (aka "map").

I'm using .completedFuture() for the example but for meaningful async work you'd create & return an (un-completed) CompletableFuture , then complete it from another thread. For example

public CompletableFuture<ObjectB> getObjectBDetails(final ObjectA a) {
    final CompletableFuture<ObjectB> promise = new CompletableFuture<>();
    new Thread(() -> {
      // work to be done..  then:
      promise.complete(a);
    }).start();
    return promise;
}

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