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:

--

--