CompletableFuture相当于flatMap的是什么?

2022-09-01 14:32:09

我有这种奇怪的类型,但我想要.这可能吗?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())
        )
    );

}

答案 1

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

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

thenCompose获取接收器的结果(调用它 1)并将其传递给您提供的,后者必须返回自己的结果(调用它 2)。返回的(称为3)将在2完成时完成。CompletableFutureFunctionCompletableFutureCompletableFuturethenCompose

在您的示例中

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

答案 2

推荐