BACK
Use casesCancel on destroy — takeUntil(destroy$)
Use cases · 07

Cancel on destroy — takeUntil(destroy$)

Pattern

The most common leak in Angular is a forgotten subscription to an interval/Subject. If the component is destroyed but the subscription lives on, it keeps poking a DOM that no longer exists.

The takeUntil(destroy$) idea

In the component, create a single Subjectdestroy$. In ngOnDestroy, call destroy$.next(); destroy$.complete();. Wrap all your streams in takeUntil(destroy$) and they unsubscribe all at once, automatically.

What we achieve

No leaks, no manual bookkeeping of a subscription array, and it's tested in one shot.

script.ts // TypeScript
CONSOLE · Console output
Hit Run to see the result...