cantdutchthis
cantdutchthis

Reputation: 34517

rxjs combining BehaviorSubject and Zip Observables

I have the following js code.

var a = new Rx.BehaviorSubject(1);
var b = new Rx.BehaviorSubject(2);
var c = new Rx.BehaviorSubject(3);

var total = Rx.Observable.zip(a,b,c, d3.sum);

var observer1 = Rx.Observer.create(
    function (x) {
        console.log('this is an oberservation from A: ' + x);
    }
);

var observer2 = Rx.Observer.create(
    function (x) {
        console.log('this is an oberservation from TOTAL: ' + x);
    }
);

var subscription1 = a.subscribe(observer1)
var subscription2 = total.subscribe(observer2)

a.onNext(5)

The goal is that when a updates, total updates and that we can see the result printed in observer2. However the output when I run this is:

this is an oberservation from A: 1
this is an oberservation from TOTAL: 0
this is an oberservation from A: 5

Why don't I see a new total and why is the initial total wrong?

Edit

When I replace the d3.sum with function(a,b,c){return a + b + c} as the reducer function then at least the initial TOTAL score is correct. I don't know if this is a related issue but if it is I'd like to know what went wrong.

Upvotes: 0

Views: 1245

Answers (1)

cantdutchthis
cantdutchthis

Reputation: 34517

It works when using

var total = Rx.Observable.combineLatest(a,b,c, function(a,b,c){return a + b + c})

The code before waits until a, b and c all have changed at least once before passing a message to the observer2.

Also, see docs.

Upvotes: 2

Related Questions