What is the CompletedFuture equivalent of flatMap?

I have this weird type CompletableFuture<CompletableFuture<byte[]>> , but I want CompletableFuture<byte[]> . Is it possible?

 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()) ) ); } 
+6
source share
1 answer

There is an error in its documentation, but CompletableFuture#thenCompose is the equivalent of a flatMap . His declaration should also give you some clues.

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

thenCompose accepts the result of the CompletableFuture receiver (calls it 1 ) and passes it to the Function that you provide, which should return its own CompletableFuture (call it 2 ). CompletableFuture (name it 3 ) returned by thenCompose will be completed when 2 completes.

In your example

 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())); 
+8
source

All Articles