0

I have 2 observables that should run concurrently, the code I have now seems to be running the 2 streams sequentially. StreamA$ completes then StreamB$ begins not as expected. How can I get the streams to run concurrently with mergeMap?

ngOnInit() {
  this.streamA$ = this.streamService.getStream(1);
  this.streamB$ = this.streamService.getOtherStream(2);
}

click() {
  console.log('clicked');
  this.streamA$
    .pipe(
      mergeMap(streamData => {
        console.log(this.streamB$);
        console.log(streamData);
        return this.streamB$;
      })         )
      .subscribe(data => {
        console.log(data);
      });
}
doe
  • 445
  • 6
  • 17
  • 1
    You're looking for one of forkJoin, zip or merge. Read the docs on them to understand the differences. – Ingo Bürk Aug 15 '19 at 12:45
  • 1
    streamB doesn't "begin" when streamA completes. It begins *every time* streamA emits something. See https://rxjs-dev.firebaseapp.com/api/operators/mergeMap. I agree with Ingo. – JB Nizet Aug 15 '19 at 12:48
  • Possible duplicate of [Subscribe to multiple async http calls](https://stackoverflow.com/questions/54457374/subscribe-to-multiple-async-http-calls) – wentjun Aug 15 '19 at 22:27

1 Answers1

1

mergeMap subscribes to the inner Observable every time the outer Observable emits a value. It is true that if the outer Observable emits multiple values, the inner one will be subscribed to concurrently, but it will always go outer->inner. If you're trying to combine the two Observables, try the following instead:

merge(this.streamA$, this.streamB$).subscribe();

This will create one single Observable which combines the emissions of the two others. Does that sound like what you're looking for?

Will Alexander
  • 3,425
  • 1
  • 10
  • 17
  • oh i get it now it handles the stream outputs concurrently – doe Aug 15 '19 at 13:08
  • Once merged is it possible to check whenever a either stream A or B has requests in complete or incomplete? So if I merge it into variable mergedStream$ can I use it to control A and B's usage? – doe Aug 15 '19 at 13:28
  • I'm not sure I understand the question. When all of the internal Observables complete, the outer (merged) Observable completes. If any of them error out, the whole thing errors out. – Will Alexander Aug 15 '19 at 13:30