forked from RxSwiftCommunity/NSObject-Rx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
HasDisposeBag.swift
44 lines (34 loc) · 1.15 KB
/
HasDisposeBag.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
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)
}
}
}
}