2016-08-10 10 views
6

私はこの奇妙なタイプCompletableFuture<CompletableFuture<byte[]>>を持っていますが、私はCompletableFuture<byte[]>がほしいです。これは可能ですか?CompletableFutureのflatMapに相当するものは何ですか?

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

} 

答えて

8

あり、そのドキュメントのbugですが、方法のCompletableFuture#thenCompose家族がflatMapのと同じです。その宣言はまた

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

thenComposeあなたにいくつかの手がかりを与える必要がありCompletableFuture独自のを返さなければならない、受信機CompletableFutureの結果を取る(それを呼び出す)とあなたが提供Functionに渡し(2それを呼び出します)。 ()が完了した場合、CompletableFuture()が返されます。あなたの例では

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())); 
関連する問題