简体   繁体   English

如何在 RxSwift 中取消订阅 Observable?

[英]How to unsubscribe from Observable in RxSwift?

I want to unsubscribe from Observable in RxSwift.我想在 RxSwift 中取消订阅 Observable。 In order to do this I used to set Disposable to nil.为了做到这一点,我曾经将 Disposable 设置为 nil。 But it seems to me that after updating to RxSwift 3.0.0-beta.2 this trick does not work and I can not unsubscribe from Observable:但在我看来,更新到 RxSwift 3.0.0-beta.2 后,这个技巧不起作用,我无法取消订阅 Observable:

//This is what I used to do when I wanted to unsubscribe
var cancellableDisposeBag: DisposeBag?

func setDisposable(){
    cancellableDisposeBag = DisposeBag()
}

func cancelDisposable(){
    cancellableDisposeBag = nil
}

So may be somebody can help me how to unsubscribe from Observable correctly?那么可能有人可以帮助我如何正确取消订阅 Observable?

In general it is good practice to out all of your subscriptions in a DisposeBag so when your object that contains your subscriptions is deallocated they are too.一般来说,最好将所有订阅都放在 DisposeBag 中,这样当包含订阅的对象被释放时,它们也会被释放。

let disposeBag = DisposeBag()

func setupRX() {
   button.rx.tap.subscribe(onNext : { _ in 
      print("Hola mundo")
   }).addDisposableTo(disposeBag)
}

but if you have a subscription you want to kill before hand you simply call dispose() on it when you want too但是如果你有一个订阅你想事先终止,你只需在你想要的时候调用 dispose() 就可以了

like this:像这样:

let disposable = button.rx.tap.subcribe(onNext : {_ in 
   print("Hallo World")
})

Anytime you can call this method and unsubscribe.您可以随时调用此方法并取消订阅。

disposable.dispose()

But be aware when you do it like this that it your responsibility to get it deallocated.但是请注意,当您这样做时,您有责任将其解除分配。

Follow up with answer to Shim's question跟进 Shim 的问题

let disposeBag = DisposeBag()
var subscription: Disposable?

func setupRX() {
    subscription = button.rx.tap.subscribe(onNext : { _ in 
        print("Hola mundo")
    })
    subscription?.addDisposableTo(disposeBag)
}

You can still call this method later你以后仍然可以调用这个方法

subscription?.dispose()

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

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