Skip to content

Instantly share code, notes, and snippets.

@patka817
Created May 4, 2022 08:49
Show Gist options
  • Save patka817/2b35d965a02c9962f66d3bcfc4fc84e3 to your computer and use it in GitHub Desktop.
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:)
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