Dan Dan - 3 months ago 22
TypeScript Question

How to unsubscribe from an RxJS 5 observable?

I have been using this pattern:

func myObservable() Observable<boolean> {
...
}

func myFunc() {
myObservable().subscribe((cond: boolean) => {
if (cond) {
// How do I unsubscribe here?
}
});
}


However I can't see any way to unsubscribe thereby maybe creating a memory leak.

The reason I ask is because Angular 2's HTTP client uses the same pattern - although I believe it auto-unsubscribes somehow and I would like to do the same.

Answer

You should do something like this:

func myFunc() {
   var subscription = myObservable().subscribe((cond: boolean) => {
       if (cond) {
          // How do I unsubscribe here?
           subscription.unsubscribe()
       }
   });
}