admin管理员组

文章数量:1315090

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.

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.

Share Improve this question asked Aug 14, 2016 at 8:20 DanDan 5,3235 gold badges34 silver badges66 bronze badges 1
  • 1 You need to store the return value which is a Subscription and unsubscribe from that. – Jason Goemaat Commented Aug 14, 2016 at 8:21
Add a ment  | 

1 Answer 1

Reset to default 12

You should do something like this:

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

本文标签: javascriptHow to unsubscribe from an RxJS 5 observableStack Overflow