iOS RxSwift 4.2如何使用DelegateProxy实现CBCentralManager的反应性扩展?

时间:2018-09-10 22:35:59

标签: ios reactive-programming core-bluetooth rx-swift

我正在看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)
  }
}

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}}