Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 633
Dan Avatar asked Aug 14 '16 08:08

Dan


People also ask

How do I unsubscribe from observable in RxJS?

Unsubscribing Manually One method we can use, is to unsubscribe manually from active subscriptions when we no longer require them. RxJS provides us with a convenient method to do this. It lives on the Subscription object and is simply called . unsubscribe() .

Do you need to unsubscribe from observable?

In Angular applications, it's always recommended to unsubscribe the observables to gain benefits like: Avoids Memory Leaks. Aborting HTTP requests to avoid unwanted calls.

How do you stop observable?

Good. Manually unsubscribe from each observable. To unsubscribe from an observable subscription, we must create a Subscription variable (timer$), assign the subscription to this variable, and then in the ngOnDestroy lifecycle hook unsubscribe the subscription.


1 Answers

You should do something like this:

func myFunc() {
   var subscription = myObservable().subscribe((cond: boolean) => {
       if (cond) {
          // How do I unsubscribe here?
           subscription.unsubscribe()
       }
   });
}
like image 69
Yaroslav Grishajev Avatar answered Oct 19 '22 04:10

Yaroslav Grishajev