当 observable 满足条件时,RxJS 停止 foreach

Nea*_*alv 1 rxjs typescript rxjs-pipeable-operators

我有一系列对象。我必须通过 API 调用检查每个对象,看看该对象是否符合特定促销的条件。继续使用对象调用 API 直到调用最后一个对象(其中可观察对象应返回 false,或者其中一个对象从 API 获得 true 状态)的最佳方法是什么?

目前我有这个代码,但感觉 RxJS 运算符应该有更好的方法。

checkProductForPromo(items: []) {
   const promoChecker$ = new EventEmitter<boolean>();

   items.forEach((item, key, arr) => {
        // This does a HTTP callback to the API
        this.ApiService.getProductInformation(item).subscribe(
            (product) => {
                // Based on some properties this will return true or false of the product is eligible for the promo.
                if (product.isEligibleForPromo()) {
                    promoChecker$.emit(true);
                } else if (Object.is(arr.length - 1, key)) {
                    promoChecker$.emit(false);
                }
            }
        );
    });

    return promoChecker$;
}
Run Code Online (Sandbox Code Playgroud)

Wil*_*der 5

您可以使用运算符创建 Observable from

checkItemsForPromo(items: any[]) {
  return from(items).pipe(
    concatMap(item => this.ApiService.getProductInformation(item)),
    map(product => !!product.isEligibleForPromo()),
    takeWhile(isEligible => !isEligible, true)    
  );
}
Run Code Online (Sandbox Code Playgroud)

此 Observable 按顺序调用每个项目的 API。它会等待上一个请求完成,然后再发送下一个请求。操作map员将发射设置为truefalse根据需要。

takeWhile意味着 Observable 将继续发出false直到true有值出现,此时它将完成。true传递给的参数实际上takeWhile是包含标志,这意味着 Observable在完成之前发出单个true值。

如果您只希望它在完成时发出false一次,而不是针对每个不合格的产品发出一次,请尝试distinctUntilChanged()pipe.

不要忘记订阅此方法返回的 Observable,并在必要时取消订阅。