Don Tomato
Don Tomato

Reputation: 3509

Is it possible to combine multiple observables with conditions in more elegant way?

Suppose I have the following sources:

ngOnInit(): void {
  this._reloadData().pipe(finalize(() => { "do some work at the end"; })).subscribe(() => {});
}

private _reloadData(): Observable<{}> {
  return new Observable(observer => {
    if (confition1) {
      this.service1.getData().subscribe(data1 => {
        if (data1.Property1) {
          this.service2.getData().subscribe(data2 => {
            this.data = this.processData2(data2);
            observer.next();
            observer.complete();
          }, error => {
            observer.error(error);
            observer.complete();
          })
        } else {
          this.service3.getData().subscribe(data3 => {
            this.data = this.processData3(data3);
            observer.next();
            observer.complete();
          }, error => {
            observer.error(error);
            observer.complete();
          });
        }
      }, error => {
        observer.error(error);
        observer.complete();
      });
    } else {
      this.service4.getData().subscribe(data4 => {
        this.data = this.processData4(data4);
        observer.next();
        observer.complete();
      }, error => {
        observer.error(error);
        observer.complete();
      });
    }
  });
}

In this piece of code there are several irritating places, and mostly a lot of observer.error, observer.next and observer.complete calls. It works, but I have feeling that it might be done some different, more elegant way... Is it possible to refactor it? Don't suggest to transfer this logiс to the back-end, it's impossible in my case.

Upvotes: 0

Views: 59

Answers (1)

Vikash Dahiya
Vikash Dahiya

Reputation: 5801

you can divide _reloadData() function into multiple methods and give meaningful name

private _reloadData(): Observable<{}> {
    return new Observable(observer => {
      if (confition1) {
        this._condition1(observer);
      } else {
        this._condition2(observer);
      }
    }
}

You should not call observer.complete() in every block, instead use only once while calling api (use third part of subscribe)

private _condition2(observer){
 this.service2.getData().subscribe(data2 => {
      this.data = this.processData2(data2);
      observer.next();
    }, error => {
      observer.error(error);
    }, () => {
      observer.complete();
    });
}

Upvotes: 1

Related Questions