Skip to content

Instantly share code, notes, and snippets.

@tonyarnold
Created September 11, 2020 04:34
Show Gist options
  • Save tonyarnold/dda01cec7eeae9ee2230f1f9ea60f976 to your computer and use it in GitHub Desktop.
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/
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