Skip to content

Instantly share code, notes, and snippets.

@Robuske
Created September 15, 2020 19:08
Show Gist options
  • Save Robuske/3f362a344810717351e239f0c7418155 to your computer and use it in GitHub Desktop.
Save Robuske/3f362a344810717351e239f0c7418155 to your computer and use it in GitHub Desktop.
assignWeakly
public extension Publisher where Failure == Never {
/// Assigns each element from a Publisher to a property on an object **and holds that objet weakly**.
///
/// `Combine`'s `assign` holds `object` with a strong reference, causing memory leaks on most use cases. Problem discussion and code origin [here](https://forums.swift.org/t/does-assign-to-produce-memory-leaks/29546/11)
///
/// - Parameters:
/// - keyPath: The key path of the property to assign.
/// - object: The object on which to assign the value.
/// - Returns: A cancellable instance; used when you end assignment of the received value. Deallocation of the result will tear down the subscription stream.
func assignWeakly<Root: AnyObject>(to keyPath: ReferenceWritableKeyPath<Root, Output>, on object: Root) -> AnyCancellable {
sink { [weak object] in
object?[keyPath: keyPath] = $0
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment