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

Best way to filter rxjs Observable array with an Observable filter function

考虑以下示例:

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

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

注意: 使用 toArray 的解决方案(如 中所述)对我不起作用:我的过滤器函数返回的可观察值从不完整且出于显而易见的原因 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