HappyEngineer
HappyEngineer

Reputation: 4055

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?
}

Upvotes: 5

Views: 1929

Answers (1)

Thorn G
Thorn G

Reputation: 12766

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

Upvotes: 4

Related Questions