Created
September 15, 2020 19:08
-
-
Save Robuske/3f362a344810717351e239f0c7418155 to your computer and use it in GitHub Desktop.
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
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