Swift Combine: WARNING!!! How to Avoid Memory Leaks!
With less development experience, when someone says ‘some new framework is better’, people tend to follow it blindly. However, it should always be kept in mind that new technologies also have new side effects. If you want to become a top developer, it is always good to be mindful of memory leaks. This habit is a very good habit.
Memory Leak Scenario with Combine
What do you think it will happen? Even if you explicitly set viewModel
to nil, deinit
won’t get called. This simply indicates ViewModel
is leaking memory….
What causes Memory Leak
It’s because when you are assigning userID
, you are creating strong reference on self
. How do you solve this?
Solution # 1
One way is to get rid of assign
and use sink
directly so that you can mark it with weak self
or unowned self
.
Solution # 2
Another way is to mark your stored value with @Published
annotation, and call assign(to: )
instead of assign(to: on:)
.
This way you can prevent memory leak.
Conclusion
- sink directly and avoid strong reference
- Use @Published annotation. And assign value with
assign(to:)
instead ofassign(to:,on:)