我正在看this example of using reactive extensions with Core Bluetooth。但是,它是用swift 3.0编写的,在Swift 4.2中运行时有很多错误。我对实现CBCentralManager
的反应式扩展感兴趣,以便向我提供状态事件的RX流。
我的理解是,这使代理可以从CBCentralManager接收委托事件,并使用_stateBehaviorSubject: BehaviorSubject<CBManagerState>?
将其传播给观察者。但是,该项目存在太多错误,我无法弄清楚应该在哪里切割以仅保留我想要的功能。
如何使用CBCentralManager的DelegateProxy实现反应式扩展?
extension Reactive where Base: CBCentralManager {
public var delegate: DelegateProxy {
return RxCBCentralManagerDelegateProxy.proxyForObject(base)
}
public var state: Observable<CBManagerState> {
let proxy = RxCBCentralManagerDelegateProxy.proxyForObject(base) //error here
return proxy.stateBehaviorSubject.skip(1)
}
}
答案 0 :(得分:2)
这是extension CBCentralManager : HasDelegate {
public typealias Delegate = CBCentralManagerDelegate
}
class RxCBCentralManagerDelegateProxy
: DelegateProxy<CBCentralManager, CBCentralManagerDelegate>
, DelegateProxyType
, CBCentralManagerDelegate
{
internal let stateBehaviorSubject: BehaviorSubject<CBManagerState>
init(centralManager: CBCentralManager) {
let subject = BehaviorSubject(value: centralManager.state)
stateBehaviorSubject = subject
super.init(parentObject: centralManager, delegateProxy: RxCBCentralManagerDelegateProxy.self)
}
func centralManagerDidUpdateState(_ central: CBCentralManager) {
stateBehaviorSubject.onNext(central.state)
_forwardToDelegate?.centralManagerDidUpdateState(central)
}
static func registerKnownImplementations() {
self.register { RxCBCentralManagerDelegateProxy(centralManager: $0) }
}
deinit {
stateBehaviorSubject.on(.completed)
}
}
extension Reactive where Base : CBCentralManager {
var delegate: DelegateProxy<CBCentralManager, CBCentralManagerDelegate> {
return RxCBCentralManagerDelegateProxy.proxy(for: base)
}
var state: ControlEvent<CBManagerState> {
let source = (delegate as! RxCBCentralManagerDelegateProxy)
.stateBehaviorSubject
.skip(1)
return ControlEvent(events: source)
}
}
{{1}}