doe
doe

Reputation: 455

Make concurrent requests using rxjs mergeMap() is sequential

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);
      });
}

Upvotes: 0

Views: 1071

Answers (1)

Will Alexander
Will Alexander

Reputation: 3571

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?

Upvotes: 1

Related Questions