Luca Pittori
Luca Pittori

Reputation: 3

Angular, rxjs : nested subscription fixing with flatMap

I'm quite new to angular and rxjs... I wrote some code I would like to refactor because I've been reading that what I've done happens to be an anti-pattern: nested subscriptions of observables.

I searched every place on the internet to find a solution (I hope I didn't miss something) and understood what I've to do but can't apply to my case: using the flatMap should solve. Here's the specific code:

...
observable1$: Observable<any>;
observable2$: Observable<any>;
...

constructor (...) {
...
    this.observable1$ = this.someStore.pipe(select(Selector.selectMyObs1));
    this.observable2$ = this.someStore.pipe(select(Selector.selectMyObs2));
...
}

...
this.observable1$.subscribe(val1 => {
    if (val1.error === false) {
        this.observable2$.subscribe(val2 => {
            this.someArray.push(val2);
        });
    }
});
...

The code works in some way, but I'm not sure if I'm just lucky or what. I'd like to know how to rewrite this code using flatMap, given the fact I have to make the 2nd subscribe only if the 1st doesn't retrieve any error.

Upvotes: 0

Views: 311

Answers (1)

user2216584
user2216584

Reputation: 5612

How about like this -

this.observable1$
    .pipe(
      mergeMap(val1 => {
        if(val1.error === false) {
          return this.observable2$
                     .pipe(
                       tap(val2 => {
                          this.someArray.push(val2);
                       })
                     );
        }

        return of(null);
      })
    ).subscribe();

It will avoid multiple subscribe. Here we are composing the observable.

Upvotes: 1

Related Questions