when we use subject we have to unsubscribe code example
Example 1: angular unsubscribe from observable
import { Subscription } from 'rxjs';
private searchEventSubscription: Subscription;
export class someComponent OnInit, OnDestroy {
constructor(private someService: SomeService) { }
ngOnInit() {
this.searchEventSubscription = this.someService.someMethod.subscribe(result => {
doSomething(result);
});
}
ngOnDestroy() {
this.searchEventSubscription.unsubscribe()
}
Example 2: is subscribing to a lot of events in ngonint bad
import { Subject } from "rxjs"
import { takeUntil } from "rxjs/operators"
@Component({
moduleId: __moduleName,
selector: "my-view",
templateUrl: "../views/view-route.view.html"
})
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) => { })
this.titleService.emitter2$
.pipe(takeUntil(this.componentDestroyed$))
.subscribe((data: any) => { })
this.titleService.emitterN$
.pipe(takeUntil(this.componentDestroyed$))
.subscribe((data: any) => { })
}
ngOnDestroy() {
this.componentDestroyed$.next(true)
this.componentDestroyed$.complete()
}
}