Skip to content

Instantly share code, notes, and snippets.

View Robuske's full-sized avatar

Rodrigo Cardoso Buske Robuske

View GitHub Profile
@Robuske
Robuske / Publisher+Extensions.swift
Created September 15, 2020 19:08
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 {