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

Memory Leak Scenario

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

The main source of problem

It’s because when you are assigning userID, you are creating strong reference on self. How do you solve this?

Solution # 1

Replace assign with `sink` and remove strong reference

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 1

Solution # 2

@Published and assign(to:)

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.

Solution 2


  1. sink directly and avoid strong reference
  2. Use @Published annotation. And assign value with assign(to:) instead of assign(to:,on:)



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
KD Knowledge Diet

Software Engineer, Mobile Developer living in Seoul. I hate people using difficult words. Why not using simple words? Keep It Simple Stupid!