Evan Evan - 27 days ago 12
TypeScript Question

Observable is null when unsubscribe is called

I'm trying to return an observable that will return data as follows.

getRootGroupNodes(): Observable<Group[]> {


return Observable.create(function(observer) {

var groups = [
{ groupName: "Group1" },
{ groupName: "Group2" }
]
observer.next(groups);

observer.complete();

});
}


When I try to consume it

this._loadGroupsSubscription = this._apiGroupService.getRootGroupNodes()
.retry(3)
.subscribe(
groups => {
// do somethign with groups
},
err => { this._log.logMessage("failed to retrieve groups"); },
() => {

this._loadGroupsSubscription.unsubscribe();
}
);


I get
this._loadGroupsSubscription
is
null
. Hence an exception is thrown trying to call unsubscribe on undefined. Any ideas what I'm doing wrong ? This should be basic..

Answer

It's true the variable isn't assigned inside the callback. I think there're two ways to handle this:

  1. Wrap unsubscription with setTimeout():

    setTimeout(() => _loadGroupsSubscription.unsubscribe());
    
  2. Add .delay(0) operator, which is basically the same trick:

    var _loadGroupsSubscription = getRootGroupNodes()
      .retry(3)
      .delay(0)
      .subscribe(
        groups => {
          console.log(groups);
        },
        err => { this._log.logMessage("failed to retrieve groups"); },
        () => {
          _loadGroupsSubscription.unsubscribe();
        }
    );
    

See live demo: https://jsbin.com/sunicoq/2/edit?js,console

See a slightly similar question with explanation how this works: Other operator in calculation chain than combineLatest to avoid redundant calculations

Comments