export class ExampleComponent implements OnInit, OnDestroy {
exampleSubOne: Subscription;
exampleSubTwo: Subscription;
constructor(private exampleService: ExampleService) {}
ngOnInit() {
this.exampleSubOne = this.exampleService.someFunction()
.subscribe(() => {
//do something
})
this.exampleSubTwo = this.exampleService.someOtherFunction()
.subscribe(() => {
//do something
})
}
ngOnDestroy(): void {
this.exampleSubOne.unsubscribe();
this.exampleSubTwo.unsubscribe();
}
}
}
export class ExampleComponent implements OnInit, OnDestroy {
private unsubscribe$ = new Subject();
constructor(private exampleService: ExampleService) {}
ngOnInit() {
this.exampleSubOne = this.exampleService.someFunction()
.pipe (takeUntil(unsubscribe$) )
.subscribe(() => {
//do something
});
this.exampleSubTwo = this.exampleService.someOtherFunction()
.pipe (takeUntil(unsubscribe$) )
.subscribe(() => {
//do something
});
}
ngOnDestroy(): void {
this.unsubscribe$.next ();
this.unsubscribe$.unsubscribe();
}
}
}
export class AsyncPipeExampleComponent implements OnInit {
exampleSubscription: Observable;
constructor(private exampleService: ExampleService) {}
ngOnInit() {
this.exampleSubscription = this.exampleService.getMessage();
}
}
}
// in html
{{ exampleSubscription | async }}
/ **
* use unsubscribe() for setInterval()
*/
function subscribe(observer) {
var intervalID = setInterval(() => {
observer.next (' hi' );
}, 1000);
return function unsubscribe() {
clearInterval(intervalID);
};
}
var unsubscribe = subscribe({next : (x) => console.log (x)});
// Later:
unsubscribe(); // dispose the resources
Storing Subscriptions in an Array
let subs: Subscription[] = [];
ngOnInit() {
this.subs.push (this.service.Subject1.subscribe(() => {}));
this.subs.push (this.service.Subject2.subscribe(() => {}));
this.subs.push (this.service.Subject3.subscribe(() => {}));
}
ngOnDestroy() {
subs.forEach(sub => sub .unsubscribe());
}
/ /===== or use Subscription.add
let subs: Subscription[] = [];
ngOnInit() {
this.subs.push(this.service.Subject1.subscribe(() => {}));
this.subs.push(this.service.Subject2.subscribe(() => {}));
this.subs.push(this.service.Subject3.subscribe(() => {}));
}
ngOnDestroy() {
subs.forEach(sub => sub.unsubscribe());
}