Search code examples
iosswiftrx-swift

Rxswift: Disposing a subscription is not disposing


I am pretty new to Rxswift and i am facing a problem

I have an Observable, i do the binding\subscription in the viewModel Init, the screen is reused soo the subscription happens every time init method runs and because of that i have two subscriptions and then when events get sent from the stream, the subscription runs twice. what i would like to happen is that when viewDidload runs to cancel the existing subscriptions and i hope that will prevent the multiple subscriptions and when an even it sent it wont run twice.

``func bind() { // this called on viewDidLoad

disposeBag = DisposeBag()

Observable
.skip(1)
.distinctUntilChanged()
.subscribe(onNext: { [weak self] visibility in
  self?.delegate?.handleChange(visibility)
 })
  .disposed(by: disposeBag)``

so what iv tried is resetting the disposeBag so that it cancels the existing subscription and subscribes again, but the subscriptions doesn't dispose when this line runs disposeBag = DisposeBag() which still results in multiple subscriptions, how can i solve this


Solution

  • You have misinterpreted the problem. The viewDidLoad method only gets called once on an object. There is no need to replace your dispose bag.

    The reason you are running multiple subscriptions is because you are using the same Observable in multiple contexts. So for example you are subscribing to the observable twice, or you are subscribing to it and using it in another operator (like combineLatest or withLatestFrom.) These cause a second subscription.

    The solution is to call .share() before adding any subscriptions. That way the separate subscriptions will share the side effect instead of each subscription getting its own side effect.