How to get your own Java futures back?

In Java 8, I am writing a DAO method that calls a method that returns a ListenableFuture (in this case, it is an asynchronous Cassandra request that returns a ResultSetFuture).

However, I was fixated on how I should return the Future to the calling DAO method. I can't just return a ResultSetFuture, because this future returns a ResultSet. I want to process a ResultSet and return another 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?
}
+4
source share
1 answer

Since you are using Guava ListenableFuture, the easiest solution is to transform the method from Futures:

ListenableFuture, .

, Java 8, :

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

Source: https://habr.com/ru/post/1614203/


All Articles