使用下面的代码,我每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)
})
注意:我希望过滤器在时间限制后发生。
答案 0 :(得分:3)
这样做的一种方法是:
flatMap
调用异步函数,返回用于过滤的值和结果; 在你的情况下,可能是这样的:
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)
})