BACK
Lessons37. finalize: cleanup after completion or error
Lessons · 37

37. finalize: cleanup after completion or error

finalize — cleanup "no matter what"

Remember teardown from lesson four? It let you do cleanup inside an Observable. But sometimes the cleanup belongs at the pipe level — after a specific chain of operators. That's what finalize is for.

finalize(fn) runs the function fn in three cases:

  • The stream completed successfully (complete).
  • The stream failed with an error (error).
  • The subscriber unsubscribed (unsubscribe).

The classic Angular example

this.loading = true;
this.http.get(...).pipe(
  finalize(() => this.loading = false)
).subscribe(...)
// whatever the outcome — the indicator goes away

The log order

Important: finalize runs after the subscriber's complete, not before. So in this lesson the order is: Value: Data → Complete → Cleanup.

Your task

  1. In pipe, add finalize(() => console.log('Cleanup')).
Solution spoiler · click to reveal
const { of, finalize } = Rx;

const request$ = of('Data').pipe(
  finalize(() => console.log('Cleanup'))
);

request$.subscribe({
  next: value => console.log('Value: ' + value),
  complete: () => console.log('Complete'),
});
script.ts // TypeScript
CONSOLE · Console output
Hit Run to see the result...