Within our Angular
application, we have implemented a unique concept using a Base Component
to manage observable subscriptions throughout the entire app. When a component subscribes to an observable, it must extend
the Base Component
. This approach ensures that all subscriptions remain active until the entire application is finally destroyed
, rather than being destroyed with each individual component:
base.component.ts:
import { Subject } from 'rxjs';
import { OnDestroy, Component } from '@angular/core';
export abstract class BaseComponent implements OnDestroy {
protected unsubscribe$ = new Subject<void>();
ngOnDestroy(): void {
this.unsubscribe$.next();
this.unsubscribe$.complete();
}
}
the-rest-of-our-components.ts:
import { Component, OnInit } from '@angular/core';
import { MyService } from 'src/app/services/my.service';
import { BaseComponent } from '../base/component/base-component';
export class myComponent extends BaseComponent implements OnInit {
myProperty: string;
constructor(
private myService: MyService,
) {
super();
}
ngOnInit(): void {
this.myService.doStuff$
.pipe(takeUntil(this.unsubscribe$)) // take until baseComponent's unsubscribe$
.subscribe((data) => {
this.myProperty = data;
});
}
If multiple components extend BaseComponent
and make use of its unsubscribe$
Subject, do all the subscriptions only get unsubscribed when the entire application is closed (when Base Component
is destroyed), as opposed to when individual components are destroyed?
Is this an effective strategy you've encountered before? Is it recommended? If my assumptions hold true, it means that all subscriptions in our application will persist until the entire app is terminated. Depending on our requirements, this could be beneficial or detrimental.
Bonus question: Does Base Component
act like a singleton
? In other words, if multiple components simultaneously extend
BaseComponent
, do they share the same instance of unsubscribe$
, or does each component have its own separate instance?