简体   繁体   English

如何取消订阅RxJS 5可观察?

[英]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. 我问的原因是因为Angular 2的HTTP客户端使用相同的模式 - 虽然我相信它会以某种方式自动取消订阅,我也想这样做。

You should do something like this: 你应该做这样的事情:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM