RxJS 中是否存在与“race"运算符相反的运算符? [英] Is-there an opposite of the `race` operator in RxJS?
问题描述
我有两个可观察对象,我想听最后一个发出第一个值的可观察对象,是否有操作符?类似的东西:
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.Observable.timer(500,500);
let obs2 = Rx.Observable.timer(1000,1000); // I want the values from this one
let sloth = Rx.Observable.sloth(obs1,obs2);
sloth
observable 会从 obs2
发出值,因为它最后发出第一个值.
where the sloth
observable would emit the values from obs2
as it is the one who emits its first value last.
如果不是这样,还有其他方法吗?
If that's not the case, is there any other way ?
推荐答案
我现在看到了这种可能性,但我很好奇是否有人发现了其他任何东西 :
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))
<script src="https://unpkg.com/@reactivex/rxjs@5.3.0/dist/global/Rx.js"></script>
编辑 正如@user3743222 所指出的(非常好的昵称 :-D ),它不适用于热观察,但这应该没问题:
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));
<script src="https://unpkg.com/@reactivex/rxjs@5.3.0/dist/global/Rx.js"></script>
这篇关于RxJS 中是否存在与“race"运算符相反的运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!