java – CompletableFuture相当于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())
        )
    );

}

解决方法

其文档中有一个 bug,但 CompletableFuture#thenCompose系列方法相当于flatMap.它的声明也应该给你一些线索
public <U> CompletableFuture<U> thenCompose(Function<? super T,? extends CompletionStage<U>> fn)

thenCompose获取接收者CompletableFuture的结果(称之为1)并将其传递给您提供的函数,该函数必须返回自己的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()));

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...