Angular — Three alternatives for unsubscribing observables at ngOnDestroy

Liu Ting Chun
4 min readDec 9, 2022

RxJS is a common library in the world of Angular. If you have been using RxJS for some time, you may have already faced the unsubscription issue. Simply put, after making a subscription, you will always need to unsubscribe at a certain point to avoid memory leaks. We want it to happen during component ngOnDestroy in most cases. However, managing these subscriptions explicitly for each component could be troublesome and painful. Here I have summarised three alternatives that could help to generalize the unsubscription logic and make it reusable within multiple components.

Image from Which

1. Class Inheritance

Class inheritance is one of the most overlooked features in Javascript. It is extremely helpful in managing shared and reusable logic. We can utilize it to create a base component with all the resources necessary for unsubscription.

@Component(...)
class BaseComponent implements OnDestroy {
destroy$ = new Subject<void>();

ngOnDestroy() {
this.destroy$.next();
this.destroy$.complete();
}
}

We can extend this base component when there is a subscription to unsubscribe.

@Component(...)
export class HelloWorldComponent extends BaseComponent {
constructor(
private testService: TestService
) {…

--

--

Liu Ting Chun

Web developer from Hong Kong. Most interested in Angular and Vue. Currently working on a Nuxt.js + NestJS project.