Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unsubscribe from Observable in RxSwift?

I want to unsubscribe from Observable in RxSwift. In order to do this I used to set Disposable to 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:

//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?

like image 378
Marina Avatar asked Oct 12 '16 11:10

Marina


People also ask

How do I cancel observable RxSwift?

To explicitly cancel a subscription, call dispose() on it. After you cancel the subscription, or dispose of it, the observable in the current example will stop emitting events.

What is RxSwift observable?

The heart of the RxSwift framework is based on observable which is also known as a sequence. Observable is the sequence of data or events which can be subscribed and can be extended by applying different Rx operators like map, filter, flatMap, etc. It can receive data asynchronously.


2 Answers

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.

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

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.

like image 66
Daniel Poulsen Avatar answered Sep 27 '22 20:09

Daniel Poulsen


Follow up with answer to Shim's question

let disposeBag = DisposeBag()
var subscription: Disposable?

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

You can still call this method later

subscription?.dispose()
like image 37
Ted Avatar answered Sep 27 '22 21:09

Ted