12

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
    You want to check if Observable has observers? – martin Aug 02 '17 at 09:39
  • yes, exactly that –  Aug 02 '17 at 09:40
  • 4
    It is still unclear why exactly you want to check for subscription before calling `unsubscribe`. You can always initialize your subscription with an empty subscription instance, e.g. `this.subscription = Subscription.EMPTY`, calling `unsubscribe` on it is safe. – Sergey Karavaev Aug 02 '17 at 10:26

4 Answers4

7

It seems you can check whether the subscription is closed with

this.subscription.closed

indicate whether this Subscription has already been unsubscribed.

HarshaXsoad
  • 776
  • 9
  • 30
5

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.

LukeIsZed
  • 69
  • 1
  • 5
2

You can check if Subject has observers because it has a public property observers.

With Observables you can't because they don't typically have arrays of observers. Only if you've multicasted them via a Subject with the multicast() operator for example.

Maybe if you could describe your use case in more detail I'll be able to give you better advice.

const source = ...;
let subscribed = false;

Rx.Observable.defer(() => {
    subscribed = true;
    return source.finally(() => { subscribed = false });
})
martin
  • 93,354
  • 25
  • 191
  • 226
1

As I can see in your code you always create a subscription.

So if you created subscriptions object it means subscription exists and you can unsubscribe.

It Still a bit not clear why you need to check is any subsection exist

Btw. unsubscribe() method checking is subscription closed or not. Subscription is closed if somebody called unsubscribe() or observable is compleated

Artem
  • 691
  • 5
  • 20