ModernMVVM icon indicating copy to clipboard operation
ModernMVVM copied to clipboard

Assign to self causes retain cycle

Open georgescumihai opened this issue 5 years ago • 4 comments

Using assign with self causes a retain cycle. https://github.com/V8tr/ModernMVVM/blob/98a36fca2061f4d3ef71d5a18948e4fa5d485e0b/ModernMVVM/Features/MovieDetails/MovieDetailViewModel.swift#L31

For more details check this forum post or stackoverflow post

georgescumihai avatar Apr 08 '20 18:04 georgescumihai

Hi @georgescumihai,

did you find solutions?

Regards

bednar avatar May 15 '20 13:05 bednar

@bednar You can see the solutions in the forum or stack overflow link.

georgescumihai avatar May 16 '20 15:05 georgescumihai

//.assign(to: \.state, on: self)
.sink{[weak self] (value) in self?.state = value}

debisani avatar Jun 22 '20 01:06 debisani

Look at this solution assignNoRetain https://forums.swift.org/t/does-assign-to-produce-memory-leaks/29546/9

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)
        }
    }
}

DanSkeel avatar Nov 29 '20 14:11 DanSkeel