Action icon indicating copy to clipboard operation
Action copied to clipboard

Retain Cycle CocoaAction

Open Marcin951 opened this issue 4 years ago • 2 comments

Hey I noticed retain cycle in this example code

    let forgotPasswordAction = CocoaAction {
        return .create { [weak self] (observer) -> Disposable in
            guard let self = self else { return Disposables.create() }
            self.delegate?.didTapForgotPasswordButton()
            
            observer.onCompleted()
            return Disposables.create()
        }
    }
    
    forgotPasswordButton.rx.action = forgotPasswordAction
    

RxSwift 6.0.0 Action latest version from master

Marcin951 avatar Jul 12 '21 10:07 Marcin951

I fixed it by moving weak self before return .create

    let forgotPasswordAction = CocoaAction { [weak self] in
        return .create { (observer) -> Disposable in
            guard let self = self else { return Disposables.create() }
            self.delegate?.didTapForgotPasswordButton()
            
            observer.onCompleted()
            return Disposables.create()
        }
    }

Now it works, but maybe that previous version of my code also should work?

Marcin951 avatar Jul 12 '21 11:07 Marcin951

In the first code snippet you posted you are implicitly capturing self via a strong reference in the WorkFactory you're declaring. You are then explicitly capturing self via a weak reference in the subscribe function you're passing to the create function that you're using to create an observable.

If self has a strong reference to the CocoaAction and the CocoaAction has a strong reference to the workFactory (and therefore self) then you have your retain cycle. There isn't any change to Action that would mitigate this (CocoaAction must have a strong reference to the workFactory to keep it in memory).

nflahavan avatar Sep 17 '22 19:09 nflahavan