How to pass data from delegate method to the observable's onNext method in RxSwift?

后端 未结 1 855
走了就别回头了
走了就别回头了 2021-01-25 23:39

I have manager class which will connect and manage the data and state of the Bluetooth device.

The manager class conforms to IWDeviceManagerDelegate and has a method whi

相关标签:
1条回答
  • 2021-01-26 00:10

    I've made a lot of assumptions in the below, but the result should look something like this:

    class WeightMachineManager {
    
        var connectedDevice: IWDevice?
    
        func setup() {
            IWDeviceManager.shared()?.initMgr()
        }
    
        func listenToWeight() -> Observable<IWWeightData> {
            if let connectedDevice = connectedDevice, let deviceManager = IWDeviceManager.shared() {
                return deviceManager.rx.add(connectedDevice)
                    .flatMap { deviceManager.rx.receivedWeightData() } // maybe this should be flatMapLatest or flatMapFirst. It depends on what is calling listenToWeight() and when.
            }
            else {
                return .error(NSError.init(domain: "WeightMachineManager", code: -1, userInfo: nil))
            }
        }
    }
    
    extension IWDeviceManager: HasDelegate {
        public typealias Delegate = IWDeviceManagerDelegate
    }
    
    class IWDeviceManagerDelegateProxy
        : DelegateProxy<IWDeviceManager, IWDeviceManagerDelegate>
        , DelegateProxyType
        , IWDeviceManagerDelegate {
    
        init(parentObject: IWDeviceManager) {
            super.init(parentObject: parentObject, delegateProxy: IWDeviceManagerDelegateProxy.self)
        }
    
        public static func registerKnownImplementations() {
            self.register { IWDeviceManagerDelegateProxy(parentObject: $0) }
        }
    }
    
    extension Reactive where Base: IWDeviceManager {
    
        var delegate: IWDeviceManagerDelegateProxy {
            return IWDeviceManagerDelegateProxy.proxy(for: base)
        }
    
        func add(_ device: IWDevice) -> Observable<Void> {
            return Observable.create { observer in
                self.base.add(device, callback: { device, code in
                    if code == .success {
                        observer.onNext(())
                        observer.onCompleted()
                    }
                    else {
                        observer.onError(NSError.init(domain: "IWDeviceManager", code: -1, userInfo: nil))
                    }
                })
                return Disposables.create()
            }
        }
    
        func receivedWeightData() -> Observable<IWWeightData> {
            return delegate.methodInvoked(#selector(IWDeviceManagerDelegate.onReceiveWeightData(_:data:)))
                .map { $0[1] as! IWWeightData }
        }
    }
    
    0 讨论(0)
提交回复
热议问题