Android BLE RxKotlin
我正在尝试创建一个BLE服务,该服务将扫描设备,并使用rxKotlin创建一个observable,允许另一个类在找到设备时进行观察。我对如何创建允许另一个类订阅的observable感到困惑,到处都是教程。有人能给我一个如何做的指针或一个好的教程 发现设备的Bluetoothservice类回调Android BLE RxKotlin,android,kotlin,rx-java2,rx-kotlin2,Android,Kotlin,Rx Java2,Rx Kotlin2,我正在尝试创建一个BLE服务,该服务将扫描设备,并使用rxKotlin创建一个observable,允许另一个类在找到设备时进行观察。我对如何创建允许另一个类订阅的observable感到困惑,到处都是教程。有人能给我一个如何做的指针或一个好的教程 发现设备的Bluetoothservice类回调 var foundDeviceObservable: Observable<BluetoothDevice> = Observable.create { } private val s
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,
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 ->
}
}
使用行为主体
//创建行为主体
var foundDeviceObservable:BehaviorSubject=BehaviorSubject()
//调用onNext()发送新找到的设备
foundDeviceObservable.onNext(foundDevice)
//您的逻辑是否使用foundDeviceObservable
foundDeviceObservable.subscribe(…)
谢谢!正因为如此,我才想出了解决办法,并睡了个好觉。然后在get函数中返回foundDeviceObservable。我将不得不研究更多的rxkotlin,我没有意识到行为主体是一条路要走。
var foundDeviceObservable: BehaviorSubject<BluetoothDevice> = BehaviorSubject.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,
address,
result.device.type.toString()
)
foundDeviceObservable.onNext(foundDevice)
}
}
}