RoyBarOn
RoyBarOn

Reputation: 987

How to merge / unite multiple RxJX Observable?

I'm using Angular 8 with RxJs and i was wonder whether it's a good practice to subscribe to multiple Observables this way, or there is a better approach to merge the responses and later, use their values.

// First create a Subscription array to add all the Observables for unsubscribe from them easily
private subs: Subscription[] = [];

// Next , push them
this.subs.push(this.myFirstSub.subscribe(res1 => {
 // Do something.
    this.subs.push(this.myFirstSub.subscribe(res2 => {
    // Do something with res1 and res2...
}))
}))

// Dispose all
ngOnDestroy(): void {
  this.subs.forEach((us) => us.unsubscribe());
}

Upvotes: 1

Views: 54

Answers (1)

kruschid
kruschid

Reputation: 779

It's not recommended to handle multiple subscriptions like that. Composing one single stream is a better practice:

private sub: Subscription;

this.sub = this.myFirstSub.pipe(
  tap(res1 => {
    // Do something.
  }),
  mergeMap(() => this.myFirstSub),
  tap(res2 => {
    // Do something with res1 and res2...
  })
)
.subscribe()

ngOnDestroy(): void {
  this.sub.unsubscribe();
}

In your case the tap operator could trigger a simple side effect (the operator wouldn't wait for async operations to complete). mergeMap subscribes to this.myFirstSub and unsubscribes automatically once we complete the outer stream with this.sub.unsubscribe()

Upvotes: 2

Related Questions