Implement unsubscribe in Angular for all application

56 Views Asked by At

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

1

There are 1 best solutions below

1
Victor David On

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.

import { Component, OnDestroy, OnInit } from '@angular/core';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';

@Component({ template: '' })
export abstract class DestroyableComponent implements OnDestroy {
  destroy$ = new Subject<void>();
  ngOnDestroy() {
    this.destroy$.next();
    this.destroy$.complete();
  }
}

@Component({
  selector: 'app-my-component',
  templateUrl: './my-component.component.html',
  styleUrls: ['./my-component.component.less'],
})
export class MyComponent extends DestroyableComponent implements OnInit {
  ngOnInit() {
    this.subToSomething()
      .pipe(takeUntil(this.destroy$))
      .subscribe(() => {});
  }
}