[英]What is CompletableFuture's equivalent of flatMap?
我有這個奇怪的類型CompletableFuture<CompletableFuture<byte[]>>
但我想要CompletableFuture<byte[]>
。 這可能嗎?
public Future<byte[]> convert(byte[] htmlBytes) {
PhantomPdfMessage htmlMessage = new PhantomPdfMessage();
htmlMessage.setId(UUID.randomUUID());
htmlMessage.setTimestamp(new Date());
htmlMessage.setEncodedContent(Base64.getEncoder().encodeToString(htmlBytes));
CompletableFuture<CompletableFuture<byte[]>> thenApply = CompletableFuture.supplyAsync(this::getPhantom, threadPool).thenApply(
worker -> worker.convert(htmlMessage).thenApply(
pdfMessage -> Base64.getDecoder().decode(pdfMessage.getEncodedContent())
)
);
}
它的文檔中有一個錯誤 ,但CompletableFuture#thenCompose
方法系列相當於flatMap
。 它的聲明也應該給你一些線索
public <U> CompletableFuture<U> thenCompose(Function<? super T,? extends CompletionStage<U>> fn)
thenCompose
獲取接收者CompletableFuture
的結果(稱之為1 )並將其傳遞給您提供的Function
,該Function
必須返回自己的CompletableFuture
(稱之為2 )。 thenCompose
返回的CompletableFuture
(稱之為3 )將在2完成時完成。
在你的例子中
CompletableFuture<Worker> one = CompletableFuture.supplyAsync(this::getPhantom, threadPool);
CompletableFuture<PdfMessage /* whatever */> two = one.thenCompose(worker -> worker.convert(htmlMessage));
CompletableFuture<byte[]> result = two.thenApply(pdfMessage -> Base64.getDecoder().decode(pdfMessage.getEncodedContent()));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.