Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxJS 6 - Do I need to unsubscribe when using first in a pipe?

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

like image 804
Kaedeko Avatar asked May 31 '18 16:05

Kaedeko


People also ask

Do I need to unsubscribe if I use take 1?

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.

Should I unsubscribe RxJS?

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.

What happens if you don't unsubscribe Angular?

🎩 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…

Does pipe subscribe to observable?

The async pipe subscribes to an Observable or Promise and returns the latest value it has emitted.


2 Answers

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();
like image 64
martin Avatar answered Oct 06 '22 19:10

martin


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.

like image 41
sojin Avatar answered Oct 06 '22 20:10

sojin