LiveLoveApp logo

Finalize Operator

finalize() Operator

To start with, you can almost think of the fnalize() operator as similar to the built-in try...catch...finally operator in JavaScript.

The finalize() operator accepts a callback function that will be invoked upon the source Observable emitting an error or completion notification, or when a subscriber unsubscribes.

Example

Let's look at an example. We'll build on the previous example for the catchError() operator:

import { Subject, throwError } from 'rxjs';
import { catchError, finalize, tap } from 'rxjs/operators';

const subject = new Subject<number>();

subject
  .pipe(
    tap((value) => {
      if (value > 1) {
        throw new Error('Error emitted by throw');
      }
    }),
    catchError(error => {
      console.error('catchError', error);
      return throwError(error).pipe(
        tap(null, (error) => {
          console.log('tap', error);
        })
      );
    }),
    finalize(() => console.log('finalize'))
  )
  .subscribe({
    error: (e) => console.error('observer', e),
    next: (value) => console.log('next', value),
    complete: () => console.log('complete')
  });

subject.next(1);
subject.next(2);

See example on codesandbox

Note the finalize() operator. In this example, the callback function provided to the finalize() operator will be invoked when the source Observable to the operator emits an error notification.