RxSwift: What is the best practice to use DisposeBag?
Asked Answered
J

2

10

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

Jemimah answered 5/8, 2018 at 13:32 Comment(0)
V
8

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.

Vander answered 8/8, 2018 at 10:1 Comment(0)
P
26

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.)

Pooch answered 8/8, 2018 at 1:32 Comment(0)
V
8

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.

Vander answered 8/8, 2018 at 10:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.