当一次足够时,RxJs反应图被调用两次

时间:2014-06-04 03:33:21

标签: javascript promise reactive-programming rxjs

在下面的示例中,每次onNext调用都会调用map两次,这是不必要的,因为ds的相同值可以重复用于两个观察者。如何编写代码,使每个onNext调用只调用一次映射?或者我应该使用诺言?

var subject = new Rx.BehaviorSubject(42);

var ds = subject.map(function(x) {
        console.log("processing");
        return x + 100;
});

var subscription1 = ds.subscribe(
    function (x) {
        console.log('first observed: ' + x.toString());
    }
);

var subscription2 = ds.subscribe(
    function (x) {
        console.log('second observed: ' + x.toString());
    }
);

subject.onNext(56);
subject.onNext(134);

1 个答案:

答案 0 :(得分:5)

最简单的方法是分享"分享"通过share运营商订阅。

这是最简单的方法:

var subject = new Rx.BehaviorSubject(42);

var ds = subject.map(function(x) {
        console.log("processing");
        return x + 100;
}).share();

var subscription1 = ds.subscribe(
    function (x) {
        console.log('first observed: ' + x.toString());
    }
);

var subscription2 = ds.subscribe(
    function (x) {
        console.log('second observed: ' + x.toString());
    }
);

subject.onNext(56);
subject.onNext(134);

// => processing
// => first observed: 142
// => processing
// => first observed: 156
// => second observed: 156
// => processing
// => first observed: 234
// => second observed: 234