微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

原文地址:https://www.jb51.cc/java/129616.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐