Created
May 4, 2022 08:49
-
-
Save patka817/2b35d965a02c9962f66d3bcfc4fc84e3 to your computer and use it in GitHub Desktop.
An extension that won't create reference-cycles when using assign(to:on:) or sink(receiveValue:)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension Publisher where Failure == Never { | |
func weakAssign<T: AnyObject>( | |
to keyPath: ReferenceWritableKeyPath<T, Output>, | |
on object: T | |
) -> AnyCancellable { | |
sink { [weak object] value in | |
object?[keyPath: keyPath] = value | |
} | |
} | |
func weakSink<T: AnyObject>( | |
_ weaklyCaptured: T, | |
receiveValue: @escaping (T, Self.Output) -> Void | |
) -> AnyCancellable { | |
sink { [weak weaklyCaptured] output in | |
guard let strongRef = weaklyCaptured else { return } | |
receiveValue(strongRef, output) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Original source: https://www.fadel.io/blog/posts/30-tips-to-make-you-a-better-ios-developer/?utm_source=swiftlee&utm_medium=swiftlee_weekly&utm_campaign=issue_94