【问题标题】:java vavr future multiple rest calljava vavr 未来多次休息调用
【发布时间】:2022-07-25 05:47:40
【问题描述】:

我想异步运行多个具有不同输出的 rest 调用。我将代码编写为

    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,..));

我将进行大约 4 到 5 个休息调用,我希望它们是异步的,但由于 Future 是通用的并且扩展了 Object 类,因此找不到任何其他方法来实现这一点。

有什么方法可以得到所有未来调用的结果,无论成功还是失败,我都可以使用这个

【问题讨论】:

  • 那么,是 Scala 还是 Java + Vavr,因为他们每个人都有自己的 Futures 和不同的方法和约定?
  • 是java + vavr

标签: java future completable-future vavr


【解决方案1】:

我建议使用 Future.zipWith 来获取 Tuple 的 Future 而不是 Future.sequence 来获取 Seq 的 Future,因为这样可以让您单独保留每个结果的类型。

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

如果你需要超过8个字段,那么你可以从源代码编译VAVr以获得更高的arity,你可以分层元组(Tuples of Tuples),也可以定义自己的容器类。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-08
    • 1970-01-01
    • 1970-01-01
    • 2015-11-14
    相关资源
    最近更新 更多