Android BLE RxKotlin

问题描述

我正在尝试创建一个 BLE 服务,它将扫描设备并使用 rxKotlin 创建一个 observable,这将允许另一个类在找到设备时进行观察。我对如何创建允许另一个订阅的 observable 感到困惑,而且教程到处都是。有人可以给我一个关于如何这样做的指针或一个好的教程。

发现设备的蓝牙服务类回调

var foundDeviceObservable: Observable<BluetoothDevice> = Observable.create {  }

private val scanCallback = object : ScanCallback() {
    override fun onScanResult(callbackType: Int,result: ScanResult) {
        with(result.device) {
            var foundName = if (name == null) "N/A" else name
            foundDevice = BluetoothDevice(
                foundName,address,result.device.type.toString()
            )
            foundDeviceObservable.subscribe {
               //Update Observable value?
            }
        }
    }
}

class DeviceListviewmodel(application: Application) : Androidviewmodel(application) {
    private val bluetoothService = BLEService()

    //Where I am trying to do logic with device
    fun getDeviceObservable(){
        bluetoothService.getDeviceObservable().subscribe{ it ->
        
    }
}

解决方

阅读user4097210的回复后找到了解决方案。只需要将找到的设备更改为

var foundDeviceObservable: BehaviorSubject<BluetoothDevice> = BehaviorSubject.create()

然后在回调中调用next方法

private val scanCallback = object : ScanCallback() {
    override fun onScanResult(callbackType: Int,result.device.type.toString()
            )
            foundDeviceObservable.onNext(foundDevice)
        }
    }
}

解决方法

使用行为主题

// create a BehaviorSubject
var foundDeviceObservable: BehaviorSubject<BluetoothDevice> = BehaviorSubject()

// call onNext() to send new found device
foundDeviceObservable.onNext(foundDevice)

// do your logic use foundDeviceObservable
foundDeviceObservable.subscribe(...)