3

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?

PowerLove
  • 303
  • 8
  • 25

1 Answers1

0

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

martin
  • 93,354
  • 25
  • 191
  • 226
  • Could you provide me with a plunkr if possible? because when I try that exact code in my code, zip operator doesn't emit anything.... – PowerLove Aug 29 '17 at 16:50
  • Of course you first need to subscribe and then call `next()`s :) – martin Aug 29 '17 at 17:13
  • Ugh, this is driving me nuts. I dont know why this same code wouldn't work on my Angular2 project... I just have that exact same thing in my services and I call the service, but zip doesn't emit anything :( – PowerLove Aug 29 '17 at 19:22