3

示例 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是一个 observable,它将从obsText1或返回数据obsText2,具体取决于 的值obsNumber

示例 2:

var arrOfObservables = /* an array of observables */;
var obsNumber = /* observable that produce numbers */;
var obsSelect = /* arrOfObservables[obsNumber] */;

obsSelect是一个可观察对象,它将从arrOfObservables由 . 生成的值确定的数组中返回所选可观察对象的数据obsNumber

我无法弄清楚如何使用 RxJS 来指定这种行为。在我看来,我需要能够在多个可观察对象之间动态订阅/取消订阅。

如何使用 RxJS 使这两个示例工作?

4

1 回答 1

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>

于 2013-06-28T14:43:35.827 回答