2016-08-10 26 views
6

Bu garip tür CompletableFuture<CompletableFuture<byte[]>> var ama ben CompletableFuture<byte[]> istiyorum. Mümkün mü?CompletableFuture'ın eşdeğeri flatMap nedir?

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

} 

cevap

8

Orada belgelerinde bir bug, ama yöntemlerden CompletableFuture#thenCompose ailesi flatMap eşdeğerdir. Onun beyanı da

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

thenCompose alıcı CompletableFuture sonucunu alır bazı ipuçları size vermelidir (bunu diyoruz) ve geçirir Function dönmek zorunda olduğu, temin kendisine ait CompletableFuture (2 diyoruz). thenCompose tarafından döndürülen CompletableFuture (olarak adlandırın) tamamlandığında tamamlanacaktır. Örnekte

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())); 
İlgili konular