在RxJS运算符中调用异步操作

时间:2018-02-19 23:04:38

标签: javascript asynchronous rxjs observable

使用下面的代码,我每500毫秒得到一个值,我拿了10个。

现在我想过滤掉无效值,但我想要调用的函数是异步的(但很快就会发生),我不知道如何在过滤器运算符中这样做。

this.subscription = this.input.getStream()
    .throttleTime(500)
    .filter(value => {
      // I want to filter out invalid values
      // but the function I want to call here is async
    })
    .take(10)  // and get 10 valid ones
    .subscribe(value => {
      this.values.push(value)
    })

注意:我希望过滤器在时间限制后发生

1 个答案:

答案 0 :(得分:3)

这样做的一种方法是:

  1. 使用flatMap调用异步函数,返回用于过滤的值和结果;
  2. 基于后者的过滤;那么
  3. 稍后,再次打开该值。
  4. 在你的情况下,可能是这样的:

    this.subscription = this.input.getStream()
        .throttleTime(500)
        .flatMap(value => asyncFunction(value).map(include => ({ value, include }))
        .filter(({ include }) => include)
        .take(10)
        .subscribe(({ value }) => {
          this.values.push(value)
        })