Question on Chapter 4 - Resource Counting and Disposable

On page 93, we took a look at disposing unused subscriptions. I was playing around with the code and saw some interesting behaviour. Here’s the code where we subscribe to the photosViewController’s PublishSubject observable:

// from page 94
photosViewController.selectedPhotos
  .subscribe(onNext: { [weak self] newImage in
    guard let images = self?.images else { return }
    images.value.append(newImage)
  }, onDisposed: {
    print("completed photo selection")
  })
  .addDisposableTo(photoViewController.bag)

When resource counting was enabled, it led to this output:

resources: 6
resources: 11
completed photo selection
resources: 11
completed photo selection

By adding to photoViewController’s dispose bag, the subscription is now being disposed of correctly. This makes sense, but then I tried something else that gave me an interesting result; I removed the addDisposableTo call from the code above. This capped the resources to 10.

resources: 6
resources: 10
resources: 10
resources: 10

I’m no longer getting the onDisposed print statements, but the resource count wasn’t increasing either. I was expecting resources to go up, what’s going on here?

Thanks in advance!

1 Like

Some of the “more simple” subscriptions can be disposed automatically by RxSwift, most probably this is what’s happening here (as it’s mentioned in the docs). However, I’ve no straight away explanation which ones are considered simple, so I’d suggest always use a bag for greater control over the process :slight_smile:

1 Like