[英]How to correctly fan out a list in CompletableFutures
我試圖從一個返回CompletableFuture<List>
的方法扇出到每個列表元素的另一個方法中,風扇反過來也返回一個CompletableFuture
。 之后我想從列表生成的 Futures 返回一個CompletableFuture.allOf
。
本質上,我有以下方法(假設它們在自己的服務類中,為了簡潔起見,我只是將它們組合在一起):
@Async
public CompletableFuture<List<File>> getMatchingCsvFrom(Path directory, Pattern pattern) {
...some work here
}
@Async
public CompletableFuture<Boolean> processSingleCsv(File csvFile) {
...some work here
}
我試圖這樣稱呼他們:
public CompletableFuture<Void> processDirectory(Path directory) {
CompletableFuture<List<File>> matchingCsvFrom = fileProcessingService.getMatchingCsvFrom(directory, PROCESS_PATTERN);
List<CompletableFuture<Boolean>> processFutures = matchingCsvFrom.get().stream()
.map(file -> processService.processProcessCsv(file))
.collect(Collectors.toList());
return CompletableFuture.allOf(processFutures.toArray(new CompletableFuture[0]));
}
.get()
顯然是一個問題,但我無法使用.thenApply()
、 .thenAccept()
或.thenCompose()
解決它。
不幸的是,我發現的所有其他答案都想實現相反的效果(從List<CompletableFuture>
到CompletableFuture<List>
)。 感謝任何建議!
public CompletableFuture<Void> processDirectory(Path directory) {
CompletableFuture<List<File>> matchingCsvFrom = fileProcessingService.getMatchingCsvFrom(directory, PROCESS_PATTERN);
return matchingCsvFrom.thenCompose( list -> {
var processFutures = list.stream()
.map(file -> processService.processProcessCsv(file))
.collect(Collectors.toList())
.toArray(new CompletableFuture[0]);
return CompletableFuture.allOf(processFutures);
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.