0

I want to run multiple rest calls with different output asynchronously. I am writing the code as

    Future<Either<ViolationException, Products>> products = Future.of(() -> 
        validateProducts([INPUT])
    );
    
    Future<Either<DomainException, List<Category>>> categories = Future.of(() -> validateCategory([INPUT]));
    
    Future<Seq<Either<? extends DomainException, ? extends Object>>> finalecall = Future.sequence(List.of(products, categories,..));

There are about 4 to 5 rest calls which I will make which I want to be asynchronous but since Future is generic and extending Object class, not finding any other way to achieve this.

Is there any way I can get result of all the rest calls which are of future, after all success or failure, I can use this

Levi Ramsey
  • 18,884
  • 1
  • 16
  • 30
raaeusagvc
  • 71
  • 6

1 Answers1

0

I recommend using Future.zipWith to get a Future of Tuple instead of Future.sequence to get a Future of Seq because that will allow you to keep the type of each result individually.

Future<Either<ViolationException, Products>> products =
  Future.of(() -> validateProducts([INPUT]));

Future<Either<DomainException, List<Category>>> categories =
  Future.of(() -> validateCategory([INPUT]));

Future<Either<SomeException, SomeType>> something =
  Future.of(() -> validateSomething([INPUT]));

Future<Either<OtherException, OtherType>> other =
  Future.of(() -> validateOther([INPUT]));

Future<Tuple4<
  Either<ViolationException, Products>,
  Either<DomainException, List<Category>>,
  Either<SomeException, SomeType>,
  Either<OtherException, OtherType>
>> finalecall = products
    .zip(categories)
    .zipWith(something, Tuple2::append)
    .zipWith(other, Tuple3::append);

If you need more than 8 fields, then you can compile VAVr from source to get a higher arity, you can tier Tuples (Tuples of Tuples), or you can define your own container class.

DBear
  • 312
  • 2
  • 9