18

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?

Marina
  • 1,177
  • 4
  • 14
  • 27
  • see this http://stackoverflow.com/questions/38969328/manually-disposing-a-disposebag-in-rxswift – Anbu.Karthik Oct 12 '16 at 11:04
  • Have a look at https://github.com/ReactiveX/RxSwift/blob/master/Documentation/GettingStarted.md#disposing. What you mention sounds like a bug. Maybe better to report it as an issue at https://github.com/ReactiveX/RxSwift/issues – 0x416e746f6e Oct 12 '16 at 13:28

2 Answers2

28

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.

d4Rk
  • 6,622
  • 5
  • 46
  • 60
Daniel Poulsen
  • 1,446
  • 13
  • 21
  • 3
    Can't you do both? (Add it to a dispose bag in case it doesn't get deallocated and also potentially dispose of it inside the block depending on the logic) – shim Sep 11 '17 at 20:09
  • As @shim suggests, I do both: I store a reference to the Disposable so that I can later call dispose() on it manually (thus effectively cancelling the subscription), but I also call .dispose(by: _disposeBag) when I create the subscription. – Womble Oct 29 '19 at 01:03
  • @Daniel How can apply your solution to a `BehaviorRelay` – user2924482 Dec 03 '19 at 17:22
9

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()
OhadM
  • 4,687
  • 1
  • 47
  • 57
Ted
  • 22,696
  • 11
  • 95
  • 109
  • 2
    If you have Disposable saved already in `subscription`, there is no need to add it to `disposeBag`. – Borzh Nov 19 '20 at 14:18