在我的observable
来源中,我收到一些事件,我希望针对这些事件进行过滤以进行某些异步操作。
例如:
s$.pipe(
map((x) => x + 1),
filter((x) => alreadyExist(x)))
.subscribe(...)
当alreadyExist
是异步操作时,
(检查该值是否存在于持久性存储中),它返回一个布尔值。
假设alreadyExist
返回一个承诺,该承诺会解析为布尔值,
我如何wait
退货?
请注意,我需要保持不变的值。
在过滤器返回之前,async-await
无效,并且订阅已执行。
答案 0 :(得分:3)
如果alreadyExist
返回boolean
,则可以使用mergeMap
来等待其结果,如果它是true
,则它将其映射到原始{{1 }}值。当它为x
时,它会被false
过滤掉。
filter
答案 1 :(得分:2)
您可以尝试我的建议-使用switchMap
管道
let isAlreadyExist = false; // "global" variable :)
s$.pipe(
map((x) => x + 1),
switchMap(async (x) => {
isAlreadyExist = await alreadyExist(x); // make sure alreadyExist is a promise func
return x; // "do" do nothing with your data
}),
filter((x) => isAlreadyExist)) // isAlreadyExist is value of alreadyExist func
.subscribe(...)
或者您可以了解defer
中的RxJS Observable
。