Finalize

Returns an Observable that mirrors the source Observable, but will call a specified function when the source terminates on complete or error.

It’s a good practice to have the catchError() and finalize at the top of the function because if there is a shareReplay() or any other operator that plays with the information it will probably be executed as many as need. For example:

.pipe(
  catchError(err => {
    this.loader = false;
    this.isError = true;
    this.outputMessage = `Error:${err.status}. It seems something went wrong, please try later`;
    return throwError(err);
  }),
  takeUntil(this.onDestroy$),
  finalize(() => {
    console.log('Task completed');
  })

Last updated