Unsubscribe an Observable in Angular
This Article helps you to Understand How to Unsubscribe an Observable in Angular?
To retrieve the values emitted into the Observable, we invoke the subscribe method on Observables with a callback function. In Angular, we use it in Components/Directives, particularly in the router module, NgRx, HTTP module.
Now, if we subscribe to a stream, it will remain open and values will be sent into it from anywhere in the app until we close it by invoking the unsubscribe method. If an observable remain unsubscribed, memory leaks & performance issues will result.
There are multiple ways we can unsubscribe an observable
1. Use the unsubscribe method
To release resources or stop Observable executions, a Subscription basically just has the unsubscribe() function.
When a component is being destroyed in Angular, we must unsubscribe from the Observable. Fortunately, Angular offers a ngOnDestroy hook that is called prior to the destruction of a component. This allows developers to dispatch the cleanup crew and prevent dangling subscriptions, open portals, and other potential problems from coming back to bother us in the future.
Therefore, we should set up the ngOnDestroy method and run the unsubscribe method on each Observable we utilise in an Angular component.
2. Use Async | Pipe
The async pipe returns the most recent value it has emitted and subscribes to an Observable or Promise. The async pipe marks the component to be examined for changes when a new value is emitted. To prevent any memory leaks, the asyncpipe immediately unsubscribes when the component is deleted.
The AppComponent will construct an Observable from the interval method upon instantiation. The Observable observable$ is then piped to the async Pipe in the template. The observable$ will be subscribed to by the async pipe, which will then show its value in the DOM.
As soon as the AppComponent is deleted, async pipe will stop subscribing to the observable$. Async Pipe's class has ngOnDestroy, which is called when the view it contains is destroyed.
If we utilise Observables in our components, using the async pipe is highly advantageous because it will subscribe to and unsubscribe from them. When the component is being terminated, we won't worry about forgetting to unsubscribe from them in ngOnDestroy.
3. Use RxJS take* operators
Use the Take Operators to transform each infinite observable into a finite observable.This operator initiates a single subscription. This operator initiates and completes a source subscription the number of n times supplied.
1 is used with the take operator to enable one-time, exit-only subscriptions.
As and When the interval emits its first value, the subscription$ get unsubscribed.
Warning: The subscription$ will not unsubscribe until the interval emits a value, even if the AppComponent is deleted. So it is best to make sure everything is canceled in the ngOnDestroy hook.
4. takeUntil(notifier)
Until a notifier Observable emits a value, this operator emits values from the source Observable.
There is an additional notifier subject that will emit the signal for this subscription cancellation. You can see that before we subscribe, we pipe the observable to takeUntil. When the notifier Subject emits, the takeUntil will stop emitting data from the interval and unsubscribe the observable$. The ngOnDestroy hook is the perfect location to make the notifier broadcast so that the observable$ is cancelled.
As long as the value output by the source Observable satisfies the predicate's test condition, this operator will output that value.
We use the takeWhile operator to stream the observable$ through. If the values are fewer than 10, the takeWhile operator will pass the values. The operator unsubscribes the observable$ if it encounters a value greater than or equal to 10.
The observable$ subscription will remain active until the interval broadcasts 10 values before the AppComponent is deleted if it doesn't emit up to 9 values before that point. The ngOnDestroy hook is therefore added to unsubscribe from observable$ when the component is deleted for added security.
6. Use RxJS first operator
The concatenation of take(1) and take with this operator is similar. While
If it is called without a value, it emits the first value that the source Observable emits and ends. If a predicate function is used to call it, it emits the first value of the source Observable that successfully passes the predicate function's test condition.
7. Use Decorator to automate Un-subscription
The majority of the techniques up to this point rely on the ngOnDestroy hook to ensure that, when a component is destroyed, the subscriptions are cleaned up. Even so, there have been changes that we can forget to remove in ngOnDestroy.
We can take advantage of Decorator's in our Angular projects to add the ngOnDestroy method to our components and have our components automatically unsubscribe from all of their subscriptions.
Our Angular project's classes can use this AutoUnsub as a class decorator. As you can see, it saves the first ngOnDestroy hook before creating a new one and hooking it into the class it is applied to. Therefore, the new hook is called when the class is destroyed. The functions inside it search through the class's properties; if they come across an Observable property, they unsubscribe from it. If the class has an original ngOnDestroy hook, it is then called.