[英]Can i use thenCombine/thenCompose on a CompletableFuture more than once?
Suppose I have CompletableFutures A, B and C is a runnable.假设我有 CompletableFutures A、B 和 C 是可运行的。 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? B 取决于 A 和 C 取决于 A 和 B,我可以做 A thenCompose B and B thenCombine A 所以 C 从 A 和 B 获取值,即使 B 也依赖于 A 的值?
Basically what I'm asking is - is there a way to get a CompletableFuture pipeline like this:基本上我要问的是 - 有没有办法获得像这样的 CompletableFuture 管道:
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.将CompletableFuture
组合在一起的方式没有限制。
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:或者,您可以直接从回调访问 A,如下所示:
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:如果您可以使用RxJava2 ,您可以按如下方式进行:
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);
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.