Use Rxjs takeUntil to unsubscribe
re4388
Posted on March 19, 2021
Why do we need to Unsubscribe?
The subscription will keep reference the component instance even after the component is destroyed if you DO NOT unsubscribe in some cases.
So, you have a piece of memory that is not be garbage collected (Memory leak).
Not Good. The app will slow down if we do a lot of this kind of thing.
Angular will help us to unsubscribe?
Yes, as I know, these are cases:
AsyncPipe
-
HTTP
service -
timer
observable
Let me know if you know more cases :)
So, we need to unsubscribe on other cases
1. The more straightforward way:
You make a subscription, and you shall unsubscribe it.
export class MyClass implements OnInit, OnDestroy {
private subscription: Subscription;
timer$: Observable<number>;
ngOnInit() {
this.subscription = this.timer$.subscribe(t => console.log(t);
)
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
Pro? Easy to understand.
Con? You or others who work on the same code base might forget to unsubscribe.
2. The takeUntil
way
export class MyClass implements OnInit, OnDestroy {
private readonly unsubscribe$: Subject<void> = new Subject();
timer$!: Observable<number>;
ngOnInit() {
this.timer$
.pipe(takeUntil(this.unsubscribe$))
.subscribe((t) => console.log(t));
}
ngOnDestroy() {
this.unsubscribe$.next();
this.unsubscribe$.complete();
}
}
What takeUntil
do?
I think this picture said it all!
z
ball is like the above "Subject"
when z . next, ⇒ takeUntil
will "Stop" the source Observable
As a result, the subscription method will "complete" when the unsubscribe$
subject emits
and when the unsubscribe$
subject emit? => When the component is going to destroy since ngOnDestroy
will invoke before it's going to destroy
Pro?
- The code inside
ngOnDestroy
is not going to touch again - when you subscribe, the declarative code make it explicit you made the unsubscription
Con?
I just think this logic is more complicated to understand. It required some knowledge to read code.
Actually, there's more ways to unsubscribe, and the reason I only introduce these two is because that the first one is the more simple-to-get one, and the second one the the one I had been seeing a lot in my working code base 😂
Let me know if you have questions. If you think I am not elaborate enough, feel free to see below links that I gathered for you :)
- Why It’s Important to Unsubscribe from RxJS Subscription | by Netanel Basal | Netanel Basal
- When to Unsubscribe in Angular. As you probably know when you subscribe… | by Netanel Basal | Netanel Basal
- RxJS - takeUntil
- The Best Way To Unsubscribe RxJS Observables In The Angular Applications! | by Tomas Trajan | Angular In Depth | Medium
- takeUntil - Learn RxJS
- Using the takeUntil RxJS Operator to Manage Subscriptions Declaratively | DigitalOcean
Posted on March 19, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 30, 2024