Created
June 15, 2020 08:09
-
-
Save groue/ecd860dba46ceff6861d883155d9f6db to your computer and use it in GitHub Desktop.
Combine assignWeakly
This file contains hidden or 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
| import Combine | |
| extension Publisher where Failure == Never { | |
| /// Same as assign(to:on:), but root object is not retained. | |
| func assignWeakly<Root: AnyObject>( | |
| to keyPath: ReferenceWritableKeyPath<Root, Self.Output>, | |
| on object: Root) | |
| -> AnyCancellable | |
| { | |
| var cancellable: AnyCancellable? | |
| cancellable = sink(receiveValue: { [weak object] value in | |
| if let object = object { | |
| object[keyPath: keyPath] = value | |
| } else { | |
| cancellable?.cancel() | |
| } | |
| }) | |
| return cancellable! | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment