java – CompletableFuture相当于flatMap是什么?

前端之家收集整理的这篇文章主要介绍了java – CompletableFuture相当于flatMap是什么?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有这种奇怪的类型CompletableFuture< CompletableFuture< byte []>>但我想要CompletableFuture< byte []>.这可能吗?
  1. public Future<byte[]> convert(byte[] htmlBytes) {
  2. PhantomPdfMessage htmlMessage = new PhantomPdfMessage();
  3. htmlMessage.setId(UUID.randomUUID());
  4. htmlMessage.setTimestamp(new Date());
  5. htmlMessage.setEncodedContent(Base64.getEncoder().encodeToString(htmlBytes));
  6.  
  7. CompletableFuture<CompletableFuture<byte[]>> thenApply = CompletableFuture.supplyAsync(this::getPhantom,threadPool).thenApply(
  8. worker -> worker.convert(htmlMessage).thenApply(
  9. pdfMessage -> Base64.getDecoder().decode(pdfMessage.getEncodedContent())
  10. )
  11. );
  12.  
  13. }

解决方法

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

thenCompose获取接收者CompletableFuture的结果(称之为1)并将其传递给您提供的函数,该函数必须返回自己的CompletableFuture(称之为2). ThenCompose返回的CompletableFuture(称之为3)将在2完成时完成.

在你的例子中

  1. CompletableFuture<Worker> one = CompletableFuture.supplyAsync(this::getPhantom,threadPool);
  2. CompletableFuture<PdfMessage /* whatever */> two = one.thenCompose(worker -> worker.convert(htmlMessage));
  3. CompletableFuture<byte[]> result = two.thenApply(pdfMessage -> Base64.getDecoder().decode(pdfMessage.getEncodedContent()));

猜你在找的Java相关文章