gpt4 book ai didi

iOS RxSwift 4.2 如何使用 DelegateProxy 实现 CBCentralManager 的 Reactive 扩展?

转载 作者:行者123 更新时间:2023-12-01 19:43:08 25 4
gpt4 key购买 nike

我在看this example of using reactive extensions with Core Bluetooth .但是,它是用 swift 3.0 编写的,并且在 Swift 4.2 中运行时存在许多错误。我有兴趣实现 CBCentralManager 的响应式扩展为我提供状态事件的 RX 流。

我的理解是,这允许代理从 CBCentralManager 接收委托(delegate)事件并使用 _stateBehaviorSubject: BehaviorSubject<CBManagerState>? 将它们传播给观察者。但是,该项目有太多错误,我无法弄清楚我应该在哪里削减以只保留我想要的功能。

如何使用 CBCentralManager 的 DelegateProxy 实现响应式(Reactive)扩展?

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

最佳答案

这是 CBCentralManager 的有效实现

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

关于iOS RxSwift 4.2 如何使用 DelegateProxy 实现 CBCentralManager 的 Reactive 扩展?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52266381/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com