When using web services, when is the best time to unsubscribe? In my code I have been doing this
tempFunction() {
const temp = this.myService.getById(id).subscribe(
response => this.model = response,
error => console.error(error),
final => temp.unsubscribe() // unsubscribe here
);
}
But everywhere else, I have seen this
temp: any;
tempFunction() {
temp = this.myService.getById(id).subscribe(
response => this.model = response,
error => console.error(error),
final => {}
);
}
ngOnDestroy() {
this.temp.unsubscribe(); // vs unsubscribe here
}
Is there a functional difference in how I am unsubscribing vs how everyone else is unsubscribing?
You don't need to unsubscribe from a simple web request like you have. They only fire once and will take care of the unsubscribe for you. Here is a SO question that discusses this very topic and why it is unnecessary.
As a general topic of how to unsubscribe, the best approach tends to be using this pattern of using takeUntil
. This allows you to ensure that everything is cleaned up when your component is destroyed in the cleanest way possible (without having to hold onto multiple subscriptions and calling unsubscribe
on each of them).
import { Subject } from 'rxjs/Subject';
import 'rxjs/add/operator/takeUntil';
@Component({ ... })
export class ExampleComponent implements OnInit, OnDestroy {
destroy$: Subject<boolean> = new Subject<boolean>();
ngOnInit() {
this.someMethodThatReturnsObservable(...)
.takeUntil(this.destroy$)
.subscribe(...);
this.someOtherMethodThatReturnsObservable(...)
.takeUntil(this.destroy$)
.subscribe(...);
}
ngOnDestroy() {
this.destroy$.next(true);
// Now let's also unsubscribe from the subject itself:
this.destroy$.unsubscribe();
}
}