There’re are basically two ways:
- call
unsubscribe()
on the Subscription object returned from thesubscribe()
call . - use an operator
To just unsubscribe
you could do it like this.
ngOnInit() {
this.subscription = timer(100, 100).subscribe(t => {
this.setFormData();
});
}
private setFormData() {
...
this.subscription.unsubscribe();
}
Or you can use Subject to complete the Observable via takeUntil()
operator:
this.subject = new Subject();
ngOnInit() {
timer(100, 100).pipe(
takeUntil(this.subject),
).subscribe(t => this.setFormData());
}
private setFormData() {
...
this.subject.next();
}
Have a look these as well:
- Difference between .unsubscribe to .take(1)
- RxJS: takeUntil() Angular component’s ngOnDestroy()
Jan 2019: Updated for RxJS 6