Search code examples
angularrxjs

angular subscribe to update method, when do you have to unsubscribe


I am developing an angular application that uses rxjs. All the examples I have seen have examples of how to subscribe and unsubscribe from read operations. My scenario is an update operation. I have the following code

       this.service.udpate(cliendId).subscribe(res => {
           console.log("success");
        }, err => console.log("error"));

This line of code is called every time the user clicks the update button. My question is, do I need to unsubscribe from this since this is an update operation and if so where should I do it?

The update method returns Observable<FetchResult<T>> from ApolloClient


Solution

  • You can easily limit the count of received events in your stream via take operator (use take(1) for your case). It completes the stream automatically after the specified number of values received. Here you can see the difference between "unlimited" stream and another one with take(1): https://stackblitz.com/edit/typescript-snhzh2?file=index.ts