forked from RxSwiftCommunity/NSObject-Rx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
NSObject+Rx.swift
37 lines (32 loc) · 1.12 KB
/
NSObject+Rx.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
import Foundation
import RxSwift
import ObjectiveC
fileprivate var disposeBagContext: UInt8 = 0
extension Reactive where Base: AnyObject {
func synchronizedBag<T>( _ action: () -> T) -> T {
objc_sync_enter(self.base)
let result = action()
objc_sync_exit(self.base)
return result
}
}
public extension Reactive where Base: AnyObject {
/// a unique DisposeBag that is related to the Reactive.Base instance only for Reference type
var disposeBag: DisposeBag {
get {
return synchronizedBag {
if let disposeObject = objc_getAssociatedObject(base, &disposeBagContext) as? DisposeBag {
return disposeObject
}
let disposeObject = DisposeBag()
objc_setAssociatedObject(base, &disposeBagContext, disposeObject, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return disposeObject
}
}
set {
synchronizedBag {
objc_setAssociatedObject(base, &disposeBagContext, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
}
}