Created
September 11, 2020 04:34
-
-
Save tonyarnold/dda01cec7eeae9ee2230f1f9ea60f976 to your computer and use it in GitHub Desktop.
A nifty extension that I borrowed from DeclarativeHub's ReactiveKit: https://github.com/declarativehub/reactivekit/
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
import Combine | |
import ObjectiveC.runtime | |
extension NSObject { | |
private enum AssociatedKeys { | |
static var CancellablesKey = "CancellablesKey" | |
} | |
/// A set that can be used to dispose of Combine cancellables. | |
public var cancellables: Set<AnyCancellable> { | |
get { | |
if let cancellables = objc_getAssociatedObject(self, &NSObject.AssociatedKeys.CancellablesKey) { | |
return cancellables as! Set<AnyCancellable> | |
} else { | |
let cancellables: Set<AnyCancellable> = [] | |
objc_setAssociatedObject(self, &NSObject.AssociatedKeys.CancellablesKey, cancellables, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) | |
return cancellables | |
} | |
} | |
set { | |
objc_setAssociatedObject(self, &NSObject.AssociatedKeys.CancellablesKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment