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).sub
The answer is: Unsubscribe when you are done with the subscription. If it needs to be active for the entire life of your component, then unsubscribing in ngOnDestroy
is appropriate. If you only need one output from the observable, then unsubscribing in the .subscribe()
callback makes sense. If some other condition in your app can mean the subscription is no longer needed at some arbitrary time, feel free to unsubscribe whenever needed.
The only rule is "Don't forget to unsubscribe." There's no hard rule about when to do it.