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

后端 未结 5 549
轮回少年
轮回少年 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 11:56

    I see this possibility, for now, but I'm curious if someone find anything else :

    let obs1 = Rx.Observable.timer(500,500).map(i=>`cheetah ${i}`);
    let obs2 = Rx.Observable.timer(1000,1000).map(i=>`sloth ${i}`);
    let sloth = Rx.Observable.merge(
      obs1.take(1).mapTo(obs1),
      obs2.take(1).mapTo(obs2)
    ).takeLast(1).mergeAll()
    
    sloth.subscribe(data=>console.log(data))

    Edit as pointed out by @user3743222 (very nice nickname :-D ), it would not work for hot observables, but this should be fine :

    let obs1 = Rx.Observable.timer(500,500).map(i=>`cheetah ${i}`).publish();
    let obs2 = Rx.Observable.timer(1000,1000).map(i=>`sloth ${i}`).publish();
    obs1.connect();
    obs2.connect();
    let sloth = Rx.Observable.merge(
      obs1.take(1).map((val)=>obs1.startWith(val)),
      obs2.take(1).map((val)=>obs2.startWith(val))
    ).takeLast(1).mergeAll();
        
    sloth.subscribe(data=>console.log(data));

提交回复
热议问题