Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix memory leaks with Combine subscriptions #10

Merged
merged 3 commits into from
Jun 2, 2020

Conversation

jgale
Copy link

@jgale jgale commented May 14, 2020

I was experimenting with this awesome tutorial and realized the TaskCellViewModel was never getting deallocated.

I researched it and came across this helpful Swift form post: https://forums.swift.org/t/does-assign-to-produce-memory-leaks/29546/11

Adapted quote:

Indeed there is a retain cycle with the sample code that uses assign:

The TaskCellViewModel retains the AnyCancellable (1), which retains the Subscribers.Assign subscription (2), which retains the Bar (3) in order to be able to perform the assignment. Cycle completed: the TaskCellViewModel is never deinited.

I fixed this by:

  1. Using [weak self] for the Combine subscriptions that use sink
  2. Added a extension on Publisher that makes assign not retain the object, which was from the above forum post

If you prefer not overloading the assign name I'm happy to rename it assignNoRetain or something like that for clarity.

After this change, a deinit() on TaskCellViewModel does get regularly called. I should note that I still see leaks when running this new code in Instruments, but it's a little beyond me to understand why. 😞

@peterfriese peterfriese self-assigned this May 29, 2020
@peterfriese peterfriese merged commit c7054fc into peterfriese:master Jun 2, 2020
@peterfriese
Copy link
Owner

Thanks for finding this issue and sending a fix, Jeremy!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants