简体   繁体   中英

How do I return my own futures in Java?

In Java 8, I'm writing a DAO method which calls a method that returns a ListenableFuture (in this case it's a Cassandra async query that returns a ResultSetFuture).

However, I'm stuck on how I'm supposed to return a Future to the caller of the DAO method. I can't just return the ResultSetFuture because that future returns a ResultSet. I want to process the ResultSet and return a different object. For example:

public ListenableFuture<ThingObj> queryForThingAsync(String thingId) {
    ListenableFuture<ResultSet> rsFuture = db.getSession().executeAsync(QueryBuilder.select().all().from("thingSchema","Thing").where(eq("thingId",thingId)));
    // Now what? How do I create a ListenableFuture<ThingObj> given a ListenableFuture<ResultSet> and a method that can convert a ResultSet into a ThingObj?
}

Since it appears you're using Guava's ListenableFuture , the easiest solution is the transform method from Futures :

Returns a new ListenableFuture whose result is the product of applying the given Function to the result of the given Future.

There are a few ways to use it, but since you're on Java 8, the simplest is likely with a method reference:

public ListenableFuture<ThingObj> queryForThingAsync(String thingId) {
    ListenableFuture<ResultSet> rsFuture = db.getSession().executeAsync(QueryBuilder.select().all().from("thingSchema","Thing").where(eq("thingId",thingId)));
    return Futures.transform(rsFuture, Utils::convertToThingObj);
}

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