i am looking for an easy way to implement usage of subject without all the tedious of unsubscribe. I saw this piece of code:
import { ReplaySubject, Subject, Observable } from 'rxjs';
export function componentDestroyed(component: OnDestroy): Observable<void> {
const oldNgOnDestroy: () => void = component.ngOnDestroy;
const destroyed: Subject<void> = new ReplaySubject<void>(1);
component.ngOnDestroy = () => {
oldNgOnDestroy.apply(component);
destroyed.next(undefined);
destroyed.complete();
};
return destroyed.asObservable();
}
Is this the best way so far? Currently have Angular 10 with no possibility to upgrade
You can create an abstract component that implement OnDestroy : when this component enter in ngOnDestroy, it emit an event on a subject. Then you only need to extend this abstract component in all other components and use
takeUntil()operator.