【发布时间】:2016-12-05 09:55:57
【问题描述】:
RxJS 中是否有一个像 filter() 一样工作但接受允许返回 Observable 的谓词的运算符?所以当谓词返回的 Observable 发出一个事件时,filter() 决定是否应该丢弃来自原始源的事件。
【问题讨论】:
标签: filter rxjs reactive-programming rxjs5
RxJS 中是否有一个像 filter() 一样工作但接受允许返回 Observable 的谓词的运算符?所以当谓词返回的 Observable 发出一个事件时,filter() 决定是否应该丢弃来自原始源的事件。
【问题讨论】:
标签: filter rxjs reactive-programming rxjs5
如果我理解正确,我会这样做:
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
【讨论】:
另一种方法是使用两个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));
}))
【讨论】: