RXJS - subscription trigger multiple times. Nested Subscription with multiple if else conditions

928 Views Asked by At

want to optimize the following code: multiple subscription in multiple if else statements.

consider:-

getList(): void {
    this.subs.sink = this.subscription1.subscribe((user) => {
      if (user) {
        this.method1();
      }
    });
  }

method1() {
//code
//code
if (condition){
//code
} else {
this.method2()
}

method2(){
 this.subs.sink = this.subscription2.subscribe(
      (response) => {
if(){
//code
} else {
this.method3();
}
}

method3(){
this.subs.sink = this.subcription3.subscribe(
      (response) => {
//code
}
}

this resulting in triggering multiple subscription.

Any help. Appreciated.

1

There are 1 best solutions below

0
On BEST ANSWER

There are multiple ways to streamline the multiple subscriptions. It depends what exactly the // code represents. If most of the // code are same, then you could possibly use filter to apply the condition.

The following method assumes each // code block is unique. It used switchMap to map from one observable to another. If you do not wish to forward the observable to the subscription's next block, you could return RxJS EMPTY constant. It would essentially complete the observable.

import { EMPTY } from 'rxjs';
import { switchMap } from 'rxjs/operators';

getList(): void {
  this.subs.sink = this.subscription1.pipe(
    switchMap((user: any) => {
      // code
      if (condition) {
        // code
        return EMPTY;
      }
      return this.subscription2;
    }),
    switchMap((response: any) => {
      if (condition) {
        // code
        return EMPTY;
      }
      return this.subscription3;
    })
  ).subscribe({
    next: (response: any) => {
      // response from `this.subscription3`
      // code
    },
    error: (error: any) => {
      // handle error
    }
  });
}