Merging Observable and take action when all subjects have emitted a value

955 views Asked by At

I'd like to merge observables into one and then subscribe when ALL of the subjects have emitted a value. So far, I've tried Observable.merge and Observable.zip

public A:Subject<any> = new Subject();
public B:Subject<any> = new Subject();
public C:Subject<any> = new Subject();
public D:Subject<any> = new Subject();
public Complete:Subject<any> = new Subject();

A.next(true);
B.next(true);
C.next(true);
D.next(true);

Observable.zip(A,B,C,D).subscribe(res=>{Complete.next(true)})

But if I do above, I think the subscriber will listen to any of A,B,C or D subject to emit a value, not ALL. What would be the way to wait until A,B,C and D have all emitted a value?

1

There are 1 answers

3
martin On

You can use Observable.forkJoin that waits until all source Observables emit at least one value and all of them complete. But since you're using Subjects it's very likely that they don't complete so using .zip() makes sense.

The zip() operator emits Xth only when all source emitted X values. In your case zip() will emit a single item only when all A, B, C and D emit at least one item.

However, if you use merge it'll emit every time any of A, B, C and D emit an item.

Live demo: http://jsbin.com/hihutoj/8/edit?js,output