【问题标题】:Combining Mono boolean results结合 Mono 布尔结果
【发布时间】:2020-09-25 16:51:37
【问题描述】:

我有这两种方法,它们调用异步 API 并在值存在时返回 Mono<Boolean>。为了这个例子,我返回一个随机布尔值,

private Mono<Boolean> checkFirstExists() {
  // Replacing actual API call here
  return Mono.just(Boolean.FALSE);
}

private Mono<Boolean> checkSecondExists() {
  // Replacing actual API call here
  return Mono.just(Boolean.TRUE);
}

现在,我有另一个方法应该结合这两种方法的结果,如果 checkFirstExistscheckSecondExists 为真,则简单地返回一个布尔值。

private boolean checkIfExists() {
  // Should return true if any of the underlying method returns true
  final Flux<Boolean> exists = Flux.concat(checkFirstExists(), checkSecondExists());
  return exists.blockFirst();
}

这样做的最佳方法是什么? Mono.zip 也许?任何帮助都会很棒。

【问题讨论】:

    标签: java reactor


    【解决方案1】:

    Mono.zip 是等待多个异步操作完成后再继续的正确方法。像这样的东西应该可以工作:

        return Mono.zip(checkFirstExists(), checkSecondExists(), (first, second) -> first && second);
    

    或者如果提供了一个列表:

        private boolean checkIfExists()
        {
            return allTrue(Arrays.asList(checkFirstExists(), checkSecondExists())).blockOptional().orElseThrow(() -> new IllegalStateException("Invalid State")); 
        }
    
        private Mono<Boolean> allTrue(List<Mono<Boolean>> toAggregate) 
        {
            return mergeMonos(toAggregate).map(list -> list.stream().allMatch(val -> val)); 
        }
    
        @SuppressWarnings("unchecked")
        private <T> Mono<List<T>> mergeMonos(List<Mono<T>> toAggregate) 
        {
            return Mono.zip(toAggregate, array -> Stream.of(array).map(o -> (T) o).collect(Collectors.toList())); 
        }
    

    无关注释:

    一般来说,在构建响应式流时,尽可能长时间地保持操作异步是值得的。让“checkIfExists”函数返回 Mono 而不是阻塞可能是值得的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-17
      • 1970-01-01
      • 2023-03-15
      • 1970-01-01
      • 2012-10-06
      • 2017-09-29
      • 2020-03-22
      • 1970-01-01
      相关资源
      最近更新 更多