Chapter 4 - memory leaks while using main DisposeBag

Hello, everyone.
I just recently have read Chapter 4 and have faced to some memory leak problems.
On page 88 usage of DisposeBag is described and stated, that using .dispose(by: bag) leads to memory leaks, because of bag would never released from memory.
But later on page 92 code .disposed(by: bag) was used again to dispose from PhotoWriter subscriber. As one would expect this leads to memory leaks about which reports.
Also on challenge solution in folder 04-observables-in-practice/challenges/ there is usage on code .disposed(by: bag) again.

What should be the correct solution for disposing subscription in actionSave method and in challenge solution?
Thanks in advance.

Subscriptions are being disposed of when the sequence terminates - e.g. if the observable emits a completed or an error event. The dispose bag is used to dispose of subscriptions that don’t terminate naturally (or haven’t terminated just yet)

Thanks for reply!
I also have read in book, that it’s better and simpler to add subscription to dispose bag and forget about it.
And again we need somehow to cleanup DisposeBag in MainViewController.
Can you suggest a correct way to do this?

Since MainViewController is always present you do not need to dispose the subscriptions in its bag. If you wish to manually dispose all subscriptions just release the bag from memory, e.g. set the bag property to nil.

But every time I click, for example, “Save” button, actionSave() is called and subscriptions count is increased by one and memory leaks…

@IBAction func actionSave() {
  guard let image = imagePreview.image else { return }
  .subscribe(onError: { [weak self] error in
    self?.showMessage("Error", description: error.localizedDescription)
  }, onCompleted: { [weak self] in
  .disposed(by: bag)


I cannot understand.
Why on page 88 is stated, that usage of .dispose(by: bag) leads to memory leaks?
Here we exactly create subscription to MainViewController’s bag.


This topic was automatically closed after 166 days. New replies are no longer allowed.