简体   繁体   中英

Guava CheckedFuture<X,Y> map to CheckedFuture <Z,Y> without blocking

I have recently been faced with Guava and its Asynchronous Future API.

I have a method with a similar declaration as this one bellow:

CheckedFuture<X, Y> update(final X entry)

which at some point might call a method with the following signature:

CheckedFuture<Boolean, Y> delete(final X entry)

What I have been looking at and didn't found is a way to map the result from the call to delete be mapped to CheckedFuture<X, Y> which is the return type of update .

Has anyone been able to do it without blocking the whole computation at some point by calling delete(entry).checkedGet() ?

Any help is appreciated.

NOTE: I know the Guava javadocs recommend the avoidance of CheckedFutures, but atm this is how the API is built and it's impractical to rebuild it (not meaning I'm not looking forward to it! :)

You can use Futures#transform

CheckedFuture<X, Y> update(final X entry) {
    CheckedFuture<Boolean, Y> f = delete(entry);
    ListenableFuture<X> tr = Futures.transform(f, (Function<Boolean, X>) input -> entry);
    return Futures.makeChecked(tr, input -> (Y) input.getCause());
}

CheckedFuture<Boolean, Y> delete(final X entry) {
    return Futures.immediateFailedCheckedFuture(new Y());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM