Search code examples
javascriptangularrxjssubject-observer

Why can subscribe be called on subject even after it is completed?


As per most of the blogs we don't need to explicitly unsubscribe the subjects once we call complete. I tried to subscribe the subject after calling complete on it. The complete call back was still executed.

let s = new Subject();
s.complete();

s.subscribe(
  () => {
    console.log("next");
  },
  () => {},
  () => {
    console.log("complete");
  }
);

Output: complete

Why subscribing to subject is allowed after it is completed?


Solution

  • What happens in this case is that first, a 'complete' notification is dispatched, and immediately afterwards, the subscription is unsubbed. So it still holds that you don't have to unsub manually.

    If you are wondering what's the use of subscribing in the first place, you can think of an example where we apply isEmpty operator to the subject, and do something depending on the value nexted by this operator.