[英]Combining Mono boolean results
我有這兩種方法,它們調用異步 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);
}
現在,我有另一種方法應該結合這兩種方法的結果,如果checkFirstExists
或checkSecondExists
為真,則簡單地返回一個布爾值。
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
也許? 任何幫助都會很棒。
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 而不是阻塞可能是值得的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.