RxJS filter()谓词返回Observable

3

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

2个回答

1
如果我理解你的意思正确,我会像下面这样做:
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


谢谢!我可以确认演示的行为与我的预期一致,尽管代码确实对于这种情况来说有些复杂。我将在接下来的几个小时内尝试将其应用到我心中真正的使用案例中,然后再回来告诉你结果。 - undefined

0
另一种方法是使用两个 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));
}))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接