RxSwift Memory Leak While Passing Functions to Operators

In RxSwift, we should be careful while passing functions to operators which might cause a memory leak.

In this example, our main actor is RxSwiftTest class. It creates an observable in init and passes multiplyByTwo function to map operator to transform the result. Passing the function causes observable to keep a strong reference to RxSwiftTest instance and RxSwiftTest can not get deallocated and subscription keeps living and printing the result:

We need to weakify the reference between observable and RxSwiftTest instance by changing the map closure as shown below:

Now the output would be:



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