Skip to content

Instantly share code, notes, and snippets.

@steipete
Last active September 15, 2020 19:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save steipete/4c63eb22ff191ce43449f744c6ad50f0 to your computer and use it in GitHub Desktop.
Save steipete/4c63eb22ff191ce43449f744c6ad50f0 to your computer and use it in GitHub Desktop.
import Foundation
import Combine
@available(iOS 13.0, *)
extension NSObject {
private struct AssociatedKeys {
static var disposeBag: UInt8 = 0
}
/// Stores a Combine AnyCancellable with the current object's disposeBag.
func addToDisposeBag(_ cancellable: AnyCancellable) {
synchronized {
var bag = objc_getAssociatedObject(self, &AssociatedKeys.disposeBag) as? [AnyCancellable] ?? []
bag.append(cancellable)
objc_setAssociatedObject(self, &AssociatedKeys.disposeBag, bag, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment