Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR TYPESCRIPT

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()
  }
}
Source by stackoverflow.com #
 
PREVIOUS NEXT
Tagged: #When #I #unsubscribe
ADD COMMENT
Topic
Name
7+9 =