2
votes

Im working with an Angular2 app which is run via electron. Currently I'm looking to improve performance for the app and reduce memory leaks. I understand that you need to destroy subscribers when the app is destroyed to prevent them watching for new values. But do you need to destroy a subscription which runs only once?

ObservableVar.subscribe().first((ans) => { // Wanting to use only one ans
    dostuff(ans);
}
1

1 Answers

3
votes

No you don't need to destroy a subscription that runs only once as the observable will complete by itself. This is the same if you use take(1).

Here is the RxJS doc about first and take.

You have to use them like this:

myOvservable.pipe(first()).subscribe(value => { /* do something */ });
myOvservable.pipe(take(1)).subscribe(value => { /* do something */ });

If you have multiple subscriptions to unsubscribe from, it may be worthwhile to use the takeUntil trick. You create a subject in which you feed a dummy value when you want your observables to complete:

unsubscribe = new Subject<void>();

myObs1.pipe(takeUntil(this.unsubscribe)).subscribe(value => { /* do something */ });
myObs2.pipe(takeUntil(this.unsubscribe)).subscribe(value => { /* do something */ });

// trigger the unsubscription
this.unsubscribe.next();

Note: takeUntil should be the last operator in the pipe sequence in order to avoid leaks (see this article).

You can also use the Subscription class to manage your subscriptions:

subscriptions = new Subscription();

this.subscriptions.add(myObs1.subscribe(value => { /* do something */ }));
this.subscriptions.add(myObs2.subscribe(value => { /* do something */ }));

// unsubscribe
this.subscriptions.unsubscribe();