Given the following code
function triggerAction() {
const asyncAction$ = of("value1");
asyncAction$
.clientLogin()
.pipe(
first(),
tap(val => console.log(`Test: ${val}`)),
)
.subscribe();
}
Do I need to unsubscribe? Previously when using first with patched operators, they unsubscribed themselves once the first event was emitted, but it's not immediately clear from the documentation as to if the piped operator equivalent does the same.
https://www.learnrxjs.io/operators/filtering/first.html https://rxjs-dev.firebaseapp.com/api/operators/first
These are called “finite subscriptions”. If you subscribe with a “take(1)”, as another example, it is finite and doesn't need to be unsubscribed.
No need to unsubscribe from internal observables of an application scoped service since this service never get's destroyed, unless your entire application get's destroyed, there is no real reason to unsubscribe from it and there is no chance of memory leaks.
🎩 Automagically Unsubscribe in Angular As you probably know when you subscribe to an observable or event in JavaScript, you usually need to unsubscribe at a certain point to release memory in the system. Otherwise, you will have a memory leak. A memory leak occurs when a section of memory that is no longer being…
The async pipe subscribes to an Observable or Promise and returns the latest value it has emitted.
Both RxJS 5 and RxJS 6 versions of first
work the same so you don't need to unsubscribe because it completes the chain and thus triggers dispose handlers.
If you want to be sure you can add complete
callback to your tap
and see if it gets called (you could add it to subscribe
as well):
asyncAction$
.clientLogin()
.pipe(
first(),
tap({
next: val => console.log(`Test: ${val}`),
complete: () => console.log(`Complete`),
}),
)
.subscribe();
The subscription$ will unsubscribe when the interval emits the first value. Beware, even if the AppComponent is destroyed thesubscription$ will not unsubscribe until the interval emits a value.
So it is best to make sure everything is cancelled in the ngOnDestroy hook.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With