Search code examples
swiftrx-swiftrx-cocoa

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


Solution

  • Defining DisposeBag in ViewController would help manage lifecycle of related Disposable

    Here is a simple example, in a ViewController, subscription against an API Request (for UI related data) is held by a Dispoable in DisposeBag. When the ViewController dealloced, associated DisposeBag would dispose all its Disposables.

    At that time, If the API Request is still pending, URLSessionTask.cancel would be called to avoid unnecessary forwarding (suppose the observable is well constructed).

    This behavior is very complicated to achieve using traditional callback closures.