用Observable过滤函数过滤rxjs Observable数组的最佳方法



考虑以下示例:

我有一个不完备的rxjs Observable,它为我提供了一个数字数组(例如of([1, 2, 3, 4, 5]))和一个自定义过滤函数,该函数为每个数字返回一个Observable布尔值(也是不完备的)(表示该数字是否应包含在结果中)。

我的问题:应用此筛选器的最佳运算符组合是什么?

注意:使用toArray的解决方案(如RxJs:Filter array with internal observable)对我不起作用:我的Filter函数返回的observable永远不会完成,而且由于明显的原因,toArray只能处理完成的流。

到目前为止,我想到的是这个使用scan运算符的怪物:https://stackblitz.com/edit/from-and-back-to-array?devtoolsheight=133&file=index.ts

我相信它是有效的,但我忍不住想,必须有一种更简单的方法来实现这一点。有人有主意吗?

我认为这应该有效。

const filtered$ = remoteSource$.pipe(
// if new source values come in, switch to those and discard the current values
switchMap(nums => {
// an array of observables each emitting a number if it passes the filter or else undefined
const checkedNumbers = nums.map(num => numFilter$(num).pipe(
map(isValid => isValid ? num : undefined)
));
// combine those observables
return combineLatest(checkedNumbers);
}),
// filter out undefined values, i.e. numbers that didn't pass the filter above
map(checkedNumers => checkedNumers.filter(num => num !== undefined)),
);

https://stackblitz.com/edit/from-and-back-to-array-6slvvf?file=index.ts

最新更新