Chapter 4. Disposing subscriptions — review

I did everything as it is written in the book. I didn’t add my code.

I go to the screen PhotosViewController 9 times.
I’m trying to deal with memory at this point. In the console it prints:
completed photo selection - 9 times
It would seem that everything works and you can safely turn the page.

But it opens the memory manager and there we see this:

Screenshot 2022-03-25 at 14.06.48

It turns out that this is a memory leak? Is there a mistake in the book?

Hi, that’s a great observation - I agree it’s a bit strange at first sight that disposables are still in memory even if the subscriptions are already completed.

The the disposables are just tokens that help the dispose bag automatically end and dispose of subscriptions. Therefore the bag “owns” the disposables (not the subscriptions or other objects, just the small tokens that identify the subscriptions) and it disposes of them when the bag itself is released from memory. For example - when you have a view controller with a bag property and you present the view controller on screen and then dismiss the view controller, that releases the bag (if it’s a property on the view controller) and all disposables it contains from memory.

If you cancel the subscription, the disposables are set to “disposed” but the token object still remains in the bag. It doesn’t leak, it will be released from memory when the bag is released from memory.

You get more and more disposables in the dispose bag of MainViewController because it’s never dismissed itself. If you want more fine-grained control you can have two dispose bags in MainViewController - one for the long running subscriptions, and another that you can overwrite periodically to release of all its disposables.

I hope that clears the topic a bit more.

1 Like

Thanks for the answer. Now it became clearer to me.

1 Like

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