Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxSwift: What is the best practice to use DisposeBag?

Now I need to change the app theme(colors) based on configuration API, So I am using RxCocoa, RxSwift frameworks to create observable on each view controller to apply a new theme on the app.

My question is what is the best practice for using DisposeBag:

  • Create new DisposeBag object on each view controller?
  • Or use one global DisposeBag for all observables?

Thanks in advance

like image 348
Moayad Al kouz Avatar asked Aug 05 '18 13:08

Moayad Al kouz


1 Answers

The whole point of a dispose bag is to dispose the observables it contains on destruction. A global bag is never destroyed which rather defeats its purpose. It's tantamount to ignoring disposables completely.

Ignoring them can be done as long as you know the observable will error/complete in finite time because the chain is disposed at that time anyway. For example if you use take(x) then you don't actually need a disposable because the chain will complete and get disposed after the proscribed number of items are emitted.

Also, interestingly, you don't need it when subscribing to a button tap because the tap Observable will complete and dispose when the button is deinited. I suspect the other UI elements work the same way.

Basically, the bag is there as a failsafe... (I learned something in the answering of this question. Thanks.)

like image 73
Daniel T. Avatar answered Sep 22 '22 14:09

Daniel T.