[英]Passing a CompletableFuture's result to another
I am relatively inexperienced with Java's CompletableFuture and I probably need some help with it.我对 Java 的 CompletableFuture 相对缺乏经验,我可能需要一些帮助。 Here is what I am trying to do.
这就是我想要做的。
/* I want to use the result of the future in a second one.
* So basically, what I want to do is to return the second future,
* but I don't want to block and wait for the first future to complete.
* /
CompletableFuture<TypeA> -> CompletableFuture<TypeB>
So I am wondering if there is a way to 'chain' the first future to the second one such that one single future(TypeB) will be returned.所以我想知道是否有办法将第一个未来“链接”到第二个未来,以便返回一个单一的未来(TypeB)。
The thenCompose
method does exactly that. thenCompose
方法正是这样做的。
Here is an example at https://www.baeldung.com/java-completablefuture :这是https://www.baeldung.com/java-completablefuture上的示例:
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> "Hello") .thenCompose(s -> CompletableFuture.supplyAsync(() -> s + " World")); assertEquals("Hello World", completableFuture.get());
Also have a look at the difference between thenCompose and thenComposeAsync .还要看看thenCompose 和 thenComposeAsync 之间的区别。
We had a similar problem when trying to write test code and the future that has to be tested is created in a background thread so we cannot simply chain it with the outer future that we want to use for asserting.我们在尝试编写测试代码时遇到了类似的问题,并且必须在后台线程中创建要测试的未来,因此我们不能简单地将它与我们想要用于断言的外部未来链接起来。
My colleague created the following method.我的同事创建了以下方法。
static <U> void propagateResultWhenCompleted(
final CompletionStage<U> source,
final CompletableFuture<U> target)
{
source.whenComplete((r, t) -> complete(target, r, t));
}
I wonder why this is not in the standard tool set.我想知道为什么这不在标准工具集中。 Surely it is not the idiomatic way of using futures but it is handy for some occasions.
当然,这不是使用期货的惯用方式,但在某些情况下很方便。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.