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.
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() .
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.
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.
You should do something like this:
func myFunc() {
   var subscription = myObservable().subscribe((cond: boolean) => {
       if (cond) {
          // How do I unsubscribe here?
           subscription.unsubscribe()
       }
   });
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With