Mayank Aggarwal
Mayank Aggarwal

Reputation: 161

CompositeFuture not working with Futures returning Lists

I have a specific use case for data processing where I am returning a future of type Future<List<SamplePOJO>>. I have multiple such futures which I am adding to a List.

But CompositeFuture.join() doesn't work on this list as it is asking for a List<Future> instead of a List<Future<List<SamplePOJO>>>. Is there any workaround for this?

Upvotes: 0

Views: 706

Answers (2)

Mykel Alvis
Mykel Alvis

Reputation: 1052

Here's an expanded set of example code (that I mistakenly wrote for another question and moved here).

So there exists a bug in Vert.x that causes issues with CompositeFuture.all(listoffutures), etc., at least in JDK 17, if listoffutures is of type List<Future<SomeType>> (or List<Future<?>>).

This bug might get fixed in Vert.x 5.

I got some success with the code below. The contrived example here is that I want to turn a List<Future<File>> into a Future<List<File>>.

@SuppressWarnings("rawtypes")
static List<Future> ltol(List<Future<File>> sa) {
  List<Future> l = new ArrayList<>();
  l.addAll(sa);
  return l;
}


// A contrived example of what I was doing, which uses .compose and returns
// a Future of the list of results (File objects in my case)
Future<List<File>> mymethodcall(List<Future<File>> attachments) {

    return CompositeFuture.all(ltol(attachments)).compose(files -> {
      // Note we're reading the result of the .all call in the compose
      List<File> mb = new ArrayList<>();
      files.list().stream().forEach(o -> {

        // Do whatever you need to do here with the results but they'll likely
        // need to be cast (to File, in this case).
        mb.add((File) o);
      });
      return Future.succeededFuture(mb);
    });
  }

The important step is getting your List<Future<T> into a List<Future>, if you need to. I did it by gross brute force in the static method above.

Upvotes: 0

Mirek Pluta
Mirek Pluta

Reputation: 8003

You can collect all those Future<List<SamplePOJO>> in the List<Future> instead of List<Future<List<SamplePOJO>>>.

That will make CompositeFuture.all method accept it.

        Future<List<String>> f = getFuture();
        
        List<Future> futures = new ArrayList<>();
        futures.add(f);
        
        CompositeFuture.all(futures);

Upvotes: 3

Related Questions