Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactiveX JS and TypeScript - How to unsubscribe?

I've been attempting to implement a new rxjs Observable in an Angular 2 component using TypeScript. I have created a service, MyService that returns an observable in one of its methods, e.g.,

export class MyService {

    getMyObs(){
        return new Observable(observer => {
            observer.next(42);
        });
    }
}

Then in my Angular 2 component I subscribe to this observable in OnInit, e.g.,

export class MyComponent implements OnInit {
obs: any;

constructor(private myService: MyService){};    

    ngOnInit {
        this.obs = myService.getMyObs().subscribe(data => {
            // Do stuff here...
        });
    }    
}

The RxJs documentation talks about unsubscribing from your observable such that your observable knows to no longer emit messages to your observer. Therefore, I figured I should be unsubscribing from the observable when my component gets destroyed, something like

export class MyComponent implements OnInit, OnDestroy {
obs: any;

constructor(private myService: MyService){};    

    ngOnInit {
        this.obs = myService.getMyObs().subscribe(data => {
            // Do stuff here...
        });
    } 

    ngOnDestroy {
        this.obs.unsubscribe();
    }  
}

Whilst this makes sense to me, the typescript compiler throws (and indeed the application throws) saying there is no unsubscribe method. There appears to be no such method described in the type definition files. How do I correctly unsubscribe from an observable using TypeScript?

like image 640
James B Avatar asked Aug 08 '16 11:08

James B


2 Answers

You need add unsubscribe method to your Observable., Disposing Observable Executions

return new Observable(observer => {
  observer.next(42);

  return () => {
    console.log('unsubscribe')
  }
}); 
like image 73
Oleksandr T. Avatar answered Sep 28 '22 01:09

Oleksandr T.


First create Subscription as follow.

private obs: Subscription = new Subscription();

Then assign to observable.

this.obs = myService.getMyObs().subscribe(data => {
       if(data !== null){
        this.obs.unsubscribe()
         }
    });
like image 39
Supun Dharmarathne Avatar answered Sep 28 '22 00:09

Supun Dharmarathne