Do I need to complete a Subject for it to be garbage collected?

If you look at the source for Subject.complete, you’ll find the answer:

complete() {
  if (this.closed) {
    throw new ObjectUnsubscribedError();
  }
  this.isStopped = true;
  const { observers } = this;
  const len = observers.length;
  const copy = observers.slice();
  for (let i = 0; i < len; i++) {
    copy[i].complete();
  }
  this.observers.length = 0;
}

Calling complete notifies any observers and then clears the array of observers. Unless you have an observer/subscriber that has a reference to the Subject, there is nothing in the complete implementation that would affect whether or not the Subject could be garbage collected.

RxJS pushes notifications to subscribers. Subscribers don’t hold references to the observables; it’s the other way around. So, unless you’ve explicitly created a subscriber that holds a reference to the Subject – via a closure or some other mechanism – there’s no need to call complete for garbage-collection purposes.

Leave a Comment