Answers for "angular/rxjs when should i unsubscribe from subscription"

0

Angular/RxJs When should I unsubscribe from `Subscription`

// You don't need to have bunch of subscriptions and unsubscribe manually.
// Use Subject and takeUntil combo to handle subscriptions like a boss:


import { Subject } from "rxjs"
import { takeUntil } from "rxjs/operators"

export class ViewRouteComponent implements OnInit, OnDestroy {
  componentDestroyed$: Subject<boolean> = new Subject()

  constructor(private titleService: TitleService) {}

  ngOnInit() {
    this.titleService.emitter1$
      .pipe(takeUntil(this.componentDestroyed$))
      .subscribe((data: any) => { /* ... do something 1 */ })

    this.titleService.emitter2$
      .pipe(takeUntil(this.componentDestroyed$))
      .subscribe((data: any) => { /* ... do something 2 */ })

    //...

    this.titleService.emitterN$
      .pipe(takeUntil(this.componentDestroyed$))
      .subscribe((data: any) => { /* ... do something N */ })
  }

  ngOnDestroy() {
    this.componentDestroyed$.next(true)
    this.componentDestroyed$.complete()
  }
}
Posted by: Guest on August-10-2021

Code answers related to "angular/rxjs when should i unsubscribe from subscription"

Code answers related to "TypeScript"

Browse Popular Code Answers by Language