[英]Java List of CompletableFutures to CompletableFuture List with allOf()
I have a piece of asynchronous code which contains more methods and I need to make it return CompletableFuture<List> in the end.我有一段包含更多方法的异步代码,我需要让它最后返回 CompletableFuture<List> 。
I need to use 2 methods:我需要使用两种方法:
I want to use allOf() in order to get the expected result, but I have an error and I do not know why: "no instance(s) of type variable(s) U exist so that Boolean conforms to CompletionStage".我想使用 allOf() 来获得预期的结果,但我有一个错误,我不知道为什么:“不存在 U 类型变量的实例,因此布尔值符合 CompletionStage”。 The error is at this line: .thenCompose(segmentedConfig -> finalEvents.add(segmentedConfig));
错误在这一行: .thenCompose(segmentedConfig -> finalEvents.add(segmentedConfig));
private CompletableFuture<List<Config>> getConfigs(User user) {
Queue<Config> finalEvents = new ConcurrentLinkedQueue<>();
List<CompletableFuture<Config>> completableFutureList = admin.getConfigsByType(configurationProperties.getEvents()) // returns Flux<Config>
.map(config -> {
return segmentConfig(config, user) // returns CompletableFuture<Config>
.thenCompose(segmentedConfig -> finalEvents.add(segmentedConfig));
})
.collect(Collectors.toList());
return allOf(completableFutureList)
.thenApply(list -> finalEvents);
private CompletableFuture<Void> allOf(List<CompletableFuture<Config>> futuresList) {
return CompletableFuture.allOf(futuresList.toArray(new CompletableFuture[0]));
}
private CompletableFuture<Config> segmentConfig(Config config, User user) {
return configurationApi.getSegmentedConfig(new DefaultCombinedConfigProvider<>(config), user);
}
What am I doing wrong?我究竟做错了什么?
You can not produce the list of results before the future created by allOf(completableFutureList)
has been completed.在
allOf(completableFutureList)
创建的未来完成之前,您无法生成结果列表。 Further, a Queue<Config>
won't become a List<Config>
.此外,
Queue<Config>
不会变成List<Config>
。
So, remove your attempt to produce the result list from the stream operation that produces the List<CompletableFuture<Config>>
.因此,请从生成
List<CompletableFuture<Config>>
的流操作中删除生成结果列表的尝试。 Then, add an actual operation producing the result list to allOf(completableFutureList)
.然后,将产生结果列表的实际操作添加到
allOf(completableFutureList)
。
private CompletableFuture<List<Config>> getConfigs(User user) {
List<CompletableFuture<Config>> completableFutureList
= admin.getConfigsByType(configurationProperties.getEvents())
.map(config -> segmentConfig(config, user))
.collect(Collectors.toList());
return CompletableFuture.allOf(completableFutureList.toArray(new CompletableFuture[0]))
.thenApply(voidArg -> completableFutureList.stream()
.map(CompletableFuture::join)
.collect(Collectors.toList()));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.