【问题标题】:Return Observable from RxJS filter() predicate从 RxJS filter() 谓词返回 Observable
【发布时间】:2016-12-05 09:55:57
【问题描述】:

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

【问题讨论】:

    标签: filter rxjs reactive-programming rxjs5


    【解决方案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

    【讨论】:

    • 谢谢!我可以确认演示的行为符合我的预期,尽管对于这种情况,代码确实看起来有点过于复杂。我会在接下来的几个小时内尝试将它应用到我想到的实际用例中,然后我会回来告诉你结果。
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2019-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-28
      • 2016-12-18
      • 1970-01-01
      相关资源
      最近更新 更多