java – CompletableFuture相当于flatMap是什么?
发布时间:2020-12-15 00:44:25 所属栏目:Java 来源:网络整理
导读:我有这种奇怪的类型CompletableFuture CompletableFuture byte []但我想要CompletableFuture byte [].这可能吗? public Futurebyte[] convert(byte[] htmlBytes) { PhantomPdfMessage htmlMessage = new PhantomPdfMessage(); htmlMessage.setId(UUID.rando
我有这种奇怪的类型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())); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |