Is there any way to check if source is subscribed?

Viewed 16358

Just as the title says, in Angular 2, is there any way to check if source is already subscribed? Because I have to check it before using

this.subscription.unsubscribe();

This is my code:

this.Source = Rx.Observable.timer(startTime, 60000).timeInterval().pluck('interval');

this.Subscription = this.Source
  .subscribe(data => { something }

and then I want to be sure that it is subscribed before calling unsubscribe()

4 Answers

It seems you can check whether the subscription is closed with

this.subscription.closed

indicate whether this Subscription has already been unsubscribed.

I had a similar case, I had a if condition with one optional subscribe:

if (languageIsSet) {
   // do things...
} else {
   this.langSub = this.langService.subscribe(lang => { 
      // do things...
   });
}

If you want to call unsubscribe safely (you don't know if is subscribed or not), just initialize the subscription with EMPTY instance:

private langSub: Subscription = Subscription.EMPTY;

Now you can unsubscribe without errors.

Related