在RxJS中是否有一种像filter()
一样的运算符,但它接受一个允许返回Observable的谓词?因此,当由谓词返回的Observable发出事件时,filter()
会决定原始源中的事件是否应被丢弃。
在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);
withLatestFrom
操作符,该操作符仅在其源发出时才发出。在我的情况下,源是 subject
,因此我对其具有完全控制权。然后有 filter()
可以过滤任何你想要的内容。setTimeout
回调函数中调用了 subject.next(null);
。2
4
2
4
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));
}))