2

In my program, I have a few timer(1000).subscribe() instances as well as some timer(1000, 1000).subscribe() parts.

I was experiencing some memory leak issues and was wondering if I could alleviate those by unsubscribing from timers. Unsubscribing from recurring timers seems straight forward and necessary, but do I also have to unsubscribe from timers that only emit once?

The second part of my question is if there is a better way to unsubscribe from the emitting timer than to put it into a variable like so:

const myTimer = timer(1000).subscribe(() => {
    myTimer.unsubscribe();
});

Thanks!

Janez
  • 2,336
  • 5
  • 25
  • 37
mneumann
  • 713
  • 2
  • 9
  • 42
  • 1
    You don't have to do `myTimer.unsubscribe();` like this. For details see https://stackoverflow.com/questions/38008334/angular-rxjs-when-should-i-unsubscribe-from-subscription https://medium.com/angular-in-depth/the-best-way-to-unsubscribe-rxjs-observable-in-the-angular-applications-d8f9aa42f6a0 https://medium.com/@benlesh/rxjs-dont-unsubscribe-6753ed4fda87 – martin Feb 06 '20 at 10:32

1 Answers1

6

timer will complete itself after one emission, so there's no need for unsubscribe For the alternative way to unsubscribe you can use the subscription instance. By using that, you benefit from storing all subscriptions and unsubscribe all with one call.

subs=new Subscription();
subs.add(timer(1000).subscribe())
subs.unsubscribe()
Fan Cheung
  • 10,745
  • 3
  • 17
  • 39