Futures.transform
はRxJavaのように流暢に連鎖可能ではありませんが、まだそれを使用して互いに依存するFuture
を設定できます。ここで具体例である:
final ListeningExecutorService service = MoreExecutors.listeningDecorator(Executors.newCachedThreadPool());
final ListenableFuture<FileClass> fileFuture = service.submit(() -> fileDownloader.download())
final ListenableFuture<UnzippedFileClass> unzippedFileFuture = Futures.transform(fileFuture,
//need to cast this lambda
(Function<FileClass, UnzippedFileClass>) file -> fileUnzipper.unzip(file));
final ListenableFuture<Void> deletedFileFuture = Futures.transform(unzippedFileFuture,
(Function<UnzippedFileClass, Void>) unzippedFile -> fileDeleter.delete(unzippedFile));
deletedFileFuture.get(); //or however you want to wait for the result
この例では、FileClass
のインスタンスを返すfileDownloader.download()
前提と、fileUpzipper.unzip()
FileDownloader.download()
代わりListenableFuture<FileClass>
を返す場合UnzippedFileClass
等、AsyncFunction
代わりにFunction
を使用し返します。
この例でも、簡潔にするためにJava 8ラムダを使用しています。あなたは、Java 8を使用していない場合は、代わりに、関数またはAsyncFunctionの匿名の実装を渡す:
Futures.transform(fileFuture, new AsyncFunction<FileClass, UpzippedFileClass>() {
@Override
public ListenableFuture<UnzippedFileClass> apply(final FileClass input) throws Exception {
return fileUnzipper.unzip();
}
});
ここtransform
の詳細情報:http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/util/concurrent/Futures.html#transformを(スクロールや「変換」を検索 - ディープリンクは現在壊れているように見えます)
先物は仕事をしません。ランナブルは行う。 –
@BrettOkkenグアバの道で走り回ることができますか?間違って何 – Chiron
可能重複['Futures.transform'](http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/util/concurrent/Futures.html#transform%28com.google .common.util.concurrent.ListenableFuture、%20comcompany.com.util.concurrent.AsyncFunction、%20java.util.concurrent.Executor%29)? – Joe