简体   繁体   English

什么是CompletableFuture相当于flatMap?

[英]What is CompletableFuture's equivalent of flatMap?

I have this weird type CompletableFuture<CompletableFuture<byte[]>> but i want CompletableFuture<byte[]> . 我有这个奇怪的类型CompletableFuture<CompletableFuture<byte[]>>但我想要CompletableFuture<byte[]> Is this possible? 这可能吗?

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())
        )
    );

}

There's a bug in its documentation, but the CompletableFuture#thenCompose family of methods is the equivalent of a flatMap . 它的文档中有一个错误 ,但CompletableFuture#thenCompose方法系列相当于flatMap Its declaration should also give you some clues 它的声明也应该给你一些线索

public <U> CompletableFuture<U> thenCompose(Function<? super T,? extends CompletionStage<U>> fn)

thenCompose takes the result of the receiver CompletableFuture (call it 1 ) and passes it to the Function you provide, which must return its own CompletableFuture (call it 2 ). thenCompose获取接收者CompletableFuture的结果(称之为1 )并将其传递给您提供的Function ,该Function必须返回自己的CompletableFuture (称之为2 )。 The CompletableFuture (call it 3 ) returned by thenCompose will be completed when 2 completes. thenCompose返回的CompletableFuture (称之为3 )将在2完成时完成。

In your example 在你的例子中

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