-
Notifications
You must be signed in to change notification settings - Fork 70
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #49 from RxSwiftCommunity/feature/hasDisposeBag
feature: rehabilitates the HasDisposeBag protocol
- Loading branch information
Showing
2 changed files
with
62 additions
and
1 deletion.
There are no files selected for viewing
This file contains 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
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
import Foundation | ||
import RxSwift | ||
import ObjectiveC | ||
|
||
fileprivate var disposeBagContext: UInt8 = 0 | ||
|
||
/// each HasDisposeBag offers a unique RxSwift DisposeBag instance | ||
public protocol HasDisposeBag: class { | ||
|
||
/// a unique RxSwift DisposeBag instance | ||
var disposeBag: DisposeBag { get set } | ||
} | ||
|
||
extension HasDisposeBag { | ||
|
||
func synchronizedBag<T>( _ action: () -> T) -> T { | ||
objc_sync_enter(self) | ||
let result = action() | ||
objc_sync_exit(self) | ||
return result | ||
} | ||
|
||
public var disposeBag: DisposeBag { | ||
get { | ||
return synchronizedBag { | ||
if let disposeObject = objc_getAssociatedObject(self, &disposeBagContext) as? DisposeBag { | ||
return disposeObject | ||
} | ||
let disposeObject = DisposeBag() | ||
objc_setAssociatedObject(self, &disposeBagContext, disposeObject, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) | ||
return disposeObject | ||
} | ||
} | ||
|
||
set { | ||
synchronizedBag { | ||
objc_setAssociatedObject(self, &disposeBagContext, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) | ||
} | ||
} | ||
} | ||
} | ||
|
||
|
||
|