Dan
Dan

Reputation: 5323

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.

Upvotes: 7

Views: 1967

Answers (1)

Yaroslav Grishajev
Yaroslav Grishajev

Reputation: 2137

You should do something like this:

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

Upvotes: 12

Related Questions