Return 从 RxJS filter() 谓词可观察

Return Observable from RxJS filter() predicate

RxJS 中是否有像 filter() 一样工作但接受允许返回 Observable 的谓词的运算符?因此,当谓词返回的 Observable 发出事件时 filter() 决定是否应丢弃来自原始源的事件。

如果我对你的理解正确,我会像下面那样做:

const Observable = Rx.Observable;
const Subject = Rx.Subject;

let subject = new Subject();

source = Observable.from([1,2,3,4])
  .flatMap(val => subject
    .withLatestFrom(Observable.of(val), (_, val) => val)
    .filter(val => val % 2 == 0)
  );

source.subscribe(val => console.log(val));

subject.next(null);
setTimeout(() => {
  subject.next(null);
}, 1000);

我用另一个 Observable 和 withLatestFrom 运算符包装每个值,该运算符仅在其源发出时发出。在我的例子中,来源是 subject 所以我可以完全控制它。然后是filter()可以过滤任何你想要的。

虽然,我想知道是否有更简单的解决方案...

这只打印两个值,1 秒后又打印两个值,因为我在 setTimeout 回调中调用了 subject.next(null);

2
4
2
4

观看现场演示:https://jsbin.com/gasumiz/10/edit?js,console

另一种方法是使用两个 switchMap 运算符:

const animals$ = from(['cat', 'dog', 'fish']).pipe(switchMap(animal => {

    // call webservice to determine if the animal is a mammal or not
    // this returns an observable boolean (i.e. a predicate)
    // this could be any Observable<boolean> of course
    const isMammal$: Observable<boolean> = webService.isMammal(animal);

    // when we get the result back if it's true then return the 
    // original 'animal' string (by creating a new observable with of()) 
    // if it isn't an animal then return EMPTY, which has the same effect as filtering it out
    return isMammal$.pipe(switchMap(isMammal => isMammal ? of(animal) : EMPTY));
}))