簡體   English   中英

什么是CompletableFuture相當於flatMap?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM