Suppose I have CompletableFutures A, B and C is a runnable. B depends on A and C depends on A and B, can I do A thenCompose B and B thenCombine A so C gets the value from A and B even though B depended on the value from A also?
Basically what I'm asking is - is there a way to get a CompletableFuture pipeline like this:
A -- B -- C
-------^
CompletableFuture<String> A = CompletableFuture.supplyAsync(() -> return "Hello");
CompletableFuture<String> B = A.thenApplyAsync(stringA -> return stringA + "World");
B.thenCombine(A, (stringA, StringB) -> doStuffWithAAndB(stringA, stringB));
Hope this makes sense.
It is perfectly fine to do this. There is no restriction on how you combine CompletableFuture
s together.
It is your responsibility to make sure they eventually complete, but it is not an issue here.
Alternatively, you can access A directly from a callback, like this:
CompletableFuture<String> a = CompletableFuture.supplyAsync(() -> return "Hello");
CompletableFuture<String> b = a.thenApplyAsync(stringA -> return stringA + "World");
b.thenApply(stringB -> doStuffWithAAndB(a.join(), stringB));
but this is really a matter of preference.
If you can use RxJava2 , you can do it as follows:
import io.reactivex.Observable;
public class CompletableFutureDemo {
public static void main(String[] args) {
CompletableFuture<String> a = CompletableFuture.supplyAsync(() -> "Hello");
Observable<String> obsA = Observable.fromFuture(a);
Observable<String> obsB = obsA.map(stringA -> stringA + " world");
Observable.zip(obsA, obsB, (stringA, stringB) -> {
return stringA + " " + stringB;
})
.subscribe(zipped -> {
System.out.println(zipped);
});
}
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.