Skip to content

Instantly share code, notes, and snippets.

@groue
Created June 15, 2020 08:09
Show Gist options
  • Select an option

  • Save groue/ecd860dba46ceff6861d883155d9f6db to your computer and use it in GitHub Desktop.

Select an option

Save groue/ecd860dba46ceff6861d883155d9f6db to your computer and use it in GitHub Desktop.
Combine assignWeakly
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