有条件地选择RxJS中的observable [英] Conditionally choose observable in RxJS
本文介绍了有条件地选择RxJS中的observable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道如何创建一个新的observable,它将返回两个其他observable中的一个,基于第一个observable是否为空(默认情况下不调用第二个observable)。例如:
I would like to know how to create a new observable that will return one of two other observables based on if the first observable is empty (without calling the second observable by default). Eg:
// scenario 1
let obs1 = Observable.empty();
let obs2 = Observable.of([1,2,3]);
// This line doesn't work, but is essentially what I'm attempting to do
let obs3 = (obs1.isEmpty()) ? obs2 : obs1;
obs3.subscribe( i => console.log('Next: ', i));
// Next: 1
// Next: 2
// Next: 3
// Complete
// scenario 2
let obs1 = Observable.of([6,7,8]);
let obs2 = Observable.of([1,2,3]);
// This line doesn't work, but is essentially what I'm attempting to do
let obs3 = (obs1.isEmpty()) ? obs2 : obs1;
obs3.subscribe( i => console.log('Next: ', i));
// Next: 6
// Next: 7
// Next: 8
// Complete
推荐答案
你可以试试:
let obs3 = obs1.isEmpty().map(x => x? obs2 : obs1;)
现在快速检查一下是否有效。
Will check quickly now if that would work.
是的,根据 doc ,应该没问题, as isEmpty
发出一个布尔值,如果observable为空,则为true,因此你可以用它来获取你想要的observable。
Yep, according to the doc, it should be fine, as isEmpty
emits a boolean which is true if the observable is empty, so you can use that to pick up the observable you want.
这篇关于有条件地选择RxJS中的observable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文