3

This seems to work and I am curious to know if this is safe. Take the following scenario...

In a shared service class I have:

this.subject = new Rx.Subject();

Lets say this observable has multiple subscribers.

The subject looks like so subject.observers = [Subscriber 1, Subscriber 2...Subscriber n]

If I wanted the Subject to stop notifying all subscribers, I know I can do subject.unsubscribe() and that will set subject.observers = null, but this then does not allow any future subscribers to attach to the this.subject instance.

Okay heres the question...

Instead of using subject.unsubscribe(), can I just clear out the observers array like so subject.observers.length = 0 with out causing any issues?

This then clears out all of the subscribers it was watching but still allows me to attach other subscribers in the future.

I can iterate through the subject.observers array and unsubscribe that way, but if I just clear out the observers array with out causing any memory leaks, I'd prefer the way.

mrcolombo
  • 587
  • 4
  • 19
  • What's wrong with iterating `subject.observers` and unsubscribing each one of them? – martin Sep 30 '16 at 09:04
  • definitely nothing wrong it, the question is more... "this seems to work, but are there any issues caused to the library by doing it this way? Or is everything okay?" – mrcolombo Sep 30 '16 at 16:26
  • 1
    Unsubscribing using `unsubscribe()` is a legitimate way of unsubscribing so you don't need to worry about it. Actually an Observable is obligated to return subscription that is able unsubscribe from its Observable (usually using a callback function). – martin Oct 02 '16 at 11:53
  • 1
    Generally you should not mess with internal APIs, I guess. Resetting the observers array could potentially be harmful - even if it is not harmful today it might be at some point in future releases. You should really use the standard approach here by unsubscribing all subscribers. Just use `subject.observers.forEach(obs => obs.unsubscribe())`. I see no reason not to follow best practices here. – dotcs Oct 09 '16 at 15:13
  • @chromate thanks for the advice, ill play it safe – mrcolombo Oct 10 '16 at 20:12

0 Answers0