angularrxjs

RxJS Observable, single success msg with concat operator


In the context of an Angular component I have 2 observables.

Requirements

  1. I want to execute both in sequence.
  2. If the first observable fails I don't want to run the second
  3. If either fail, I want to log a single error msg
  4. If both succeed, I want to log a single success msg

Approach

What is the best way to achieve my requirements?

    getData1$ = this.myService.getData1();
    getData2$ = this.myService.getData2();
    
    constructor(private myService: MyService) {
      this.getAllData();
    }
    
    getAllData() {
      concat(this.getData1$, this.getData2$)
      .pipe(finalize(() => console.log('always called')))
      .subscribe(() => {
        error: console.log('one or more data fetches have had an error');
        complete: console.log('all data fetches have succeeded');
      });}

Solution

  • Use a concat, it will execute in series one by one, then we can use toArray which will collect all source emissions and emits them as an array when the source completes.

    getData1$ = this.myService.getData1();
    getData2$ = this.myService.getData2();
    
    constructor(private myService: MyService) {
      this.getAllData();
    }
    
    getAllData() {
      concat(this.getData1$, this.getData2$).pipe(toArray())
      .subscribe({
        next: (data: any) => console.log('success!'),
        error: () => console.log('one or more data fetches have had an error'),
        complete: () => console.log('all data fetches have succeeded'),
      });
    }
    

    Stackblitz Demo