MarcelSauter
MarcelSauter

Reputation: 87

RxJs not switchMap if an error occured in the top level subscription

If my first Observable throws an error, then i would not subscribe to my switchMap observable.

Is this possible?

this._profileService.updateProfile(profile).pipe(
  tap(profile => {
    this.profile = profile;
    this.saving = false;
    this.updateForm(this.profile);
  }),
  catchError(error => {
    console.log(error);
    this.saving = false;
    this.updateForm();
    return this._pjNotificationService.show(PjNotificationType.ERROR, 'Fehler beim Speichern',
      `Beim Speichern ist ein Fehler aufgetreten. ${error}`, 15000)
  }),
  switchMap(() => this._pjNotificationService.show(PjNotificationType.SAVED, 'Änderungen gespeichert', '', 15000))
).subscribe();

Upvotes: 0

Views: 975

Answers (1)

Steve Holgado
Steve Holgado

Reputation: 12071

Due to the order of your operators, the observable returned by catchError will continue to the switchMap.

You can change the order of your operators so that the switchMap comes before the catchError:

this._profileService.updateProfile(profile).pipe(
  tap(profile => {
    this.profile = profile;
    this.saving = false;
    this.updateForm(this.profile);
  }),
  switchMap(() => this._pjNotificationService.show(PjNotificationType.SAVED, 'Änderungen gespeichert', '', 15000)),
  catchError(error => {
    console.log(error);
    this.saving = false;
    this.updateForm();
    return this._pjNotificationService.show(PjNotificationType.ERROR, 'Fehler beim Speichern',
      `Beim Speichern ist ein Fehler aufgetreten. ${error}`, 15000)
  })
).subscribe();

This way, the switchMap will get skipped if this._profileService.updateProfile(profile) throws an error, as it will jump to the catchError.

Upvotes: 3

Related Questions