将可观察序列转换为可观察序列,仅从最近的可观察序列产生值

时间:2013-06-28 10:43:56

标签: reactive-programming rxjs reactive-extensions-js

示例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是一个可观察的,会返回obsText1obsText2的数据,具体取决于obsNumber的值。

示例2:

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

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

我无法弄清楚如何使用RxJS指定此行为。在我看来,我需要能够在多个observable之间动态订阅/取消订阅。

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

1 个答案:

答案 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>