Created
September 29, 2017 13:51
-
-
Save pavankataria/660708a6939d0ad3a8bf44ceae4e3eaa to your computer and use it in GitHub Desktop.
A protocol for automatically adding a dispose bag to any object that requires it. Uses associated objects.
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
// | |
// HasDisposeBag.swift | |
// | |
// Created by Pavan Kataria 26/09/2017 | |
// Copyright © 2017 Pavan Kataria. All rights reserved. | |
protocol HasDisposeBag { | |
var disposeBag: DisposeBag { get } | |
} | |
private struct AssociatedKeys { | |
static var disposeBag = "pk_disposeBag" | |
} | |
extension HasDisposeBag { | |
var disposeBag: DisposeBag { | |
get { | |
if let disposeBag = objc_getAssociatedObject(self, &AssociatedKeys.disposeBag) as? DisposeBag { | |
return disposeBag | |
} | |
objc_setAssociatedObject(self, &AssociatedKeys.disposeBag, DisposeBag(), .OBJC_ASSOCIATION_RETAIN) | |
return self.disposeBag | |
} | |
set { | |
objc_setAssociatedObject(self, &AssociatedKeys.disposeBag, newValue, .OBJC_ASSOCIATION_RETAIN) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment