什么是CompletableFuture相当于flatMap?

Ric*_*ler 16 java java-8 completable-future

我有这种奇怪的类型,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())
        )
    );

}
Run Code Online (Sandbox Code Playgroud)

Sot*_*lis 22

它的文档中有一个错误,但CompletableFuture#thenCompose方法系列相当于一个flatMap.它的声明也应该给你一些线索

public <U> CompletableFuture<U> thenCompose(Function<? super T,? extends CompletionStage<U>> fn)
Run Code Online (Sandbox Code Playgroud)

thenCompose获取接收器的结果CompletableFuture(称之为1)并将其传递给Function您提供的,它必须返回它自己的CompletableFuture(称之为2).返回的CompletableFuture(调用它3)thenCompose将在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()));
Run Code Online (Sandbox Code Playgroud)