Does 'assign(to:)' produce memory leaks?

Hi everyone.

There is indeed a memory leak if self is both keeping the reference to the subscription and is the target of the assignation. I've made the following replacement that seems to do the trick.

I'm simply proxying the assignation through a sink where I can weakly refer to self. I'm using a Just publisher to let Combine manage the assignation. It seems to work as expected on my side.

extension Publisher where Self.Failure == Never {
    public func assignNoRetain<Root>(to keyPath: ReferenceWritableKeyPath<Root, Self.Output>, on object: Root) -> AnyCancellable where Root: AnyObject {
        sink { [weak object] (value) in
            guard let object = object else { return }
            _ = Just(value).assign(to: keyPath, on: object)
        }
    }
}
3 Likes