示例1:
var obsNumber = /* observable that produce numbers */;
var obsText1 = /* observable that produce text */;
var obsText2 = /* observable that produce text */;
var obsContext = /* IF obsNumber < 5 THEN obsText1 ELSE obsText2 */;
obsContext
是一个可观察的,会返回obsText1
或obsText2
的数据,具体取决于obsNumber
的值。
示例2:
var arrOfObservables = /* an array of observables */;
var obsNumber = /* observable that produce numbers */;
var obsSelect = /* arrOfObservables[obsNumber] */;
obsSelect
是一个可观察的,它将从arrOfObservables
数组中由obsNumber
生成的值确定所选观察数据。
我无法弄清楚如何使用RxJS指定此行为。在我看来,我需要能够在多个observable之间动态订阅/取消订阅。
如何使用RxJS使两个示例工作?
答案 0 :(得分:5)
使用switch
:
将可观察的可观察序列序列转换为可观察序列,仅从最近的可观察序列产生值。
示例1
var obsNumber,
obsText1,
obsText2;
obsNumber = Rx.Observable.interval(500).take(10);
obsText1 = Rx.Observable.return('a');
obsText2 = Rx.Observable.return('b');
obsNumber
.do(function (x) {
console.log('x: ' + x);
})
.map(function (x) {
return x < 5 ? obsText1 : obsText2;
})
.switch()
.subscribe(function (context) {
console.log('context: ' + context);
});
<script src='https://rawgit.com/Reactive-Extensions/RxJS/v.2.5.3/dist/rx.all.js'></script>
示例2
var obsNumber,
arrOfObservables;
obsNumber = Rx.Observable.range(0, 3);
arrOfObservables = [
Rx.Observable.return('a'),
Rx.Observable.return('b'),
Rx.Observable.return('c')
];
obsNumber
.do(function (x) {
console.log('x: ' + x);
})
.map(function (x) {
return arrOfObservables[x];
})
.switch()
.subscribe(function (context) {
console.log('context: ' + context);
});
<script src='https://rawgit.com/Reactive-Extensions/RxJS/v.2.5.3/dist/rx.all.js'></script>