Is-there an opposite of the `race` operator in RxJS?

后端 未结 5 566
轮回少年
轮回少年 2021-01-14 11:48

I have two observables and I want listen to the one that emits its first value last, is there an operator for this ? Something like that :

let obs1 = Rx.Obse         


        
5条回答
  •  情书的邮戳
    2021-01-14 12:19

    Using RxJS 6 and ReplaySubject:

    function lastOf(...observables) {
      const replayable = observables
        .map(o => {
          let r = o.pipe(multicast(new ReplaySubject(1)));
          r.connect();
          return r;
        });
      const racing = replayable
        .map((v, i) => v.pipe(
          take(1),
          mapTo(i),
        ))
        ;
      return of(...racing).pipe(
        mergeAll(),
        reduce((_, val) => val),
        switchMap(i => replayable[i]),
      );
    }
    

    Use:

    const fast = interval(500);
    const medium = interval(1000);
    const slow = interval(2000);
    
    lastOf(fast, slow, medium).subscribe(console.log);
    

提交回复
热议问题