0

I'm trying to create a BLE service that will scan for devices and using rxKotlin create an observable that will allow another class to observe when a device is found. I'm confused on how to create the observable that will allow another class to subscribe and tutorials are all over the place. Can someone give me a pointer on how to do so or a good tutorial.

Bluetoothservice class callback where devices are discovered

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

Solution

Was able to find the solution after reading user4097210's reply. Just had to change the found device to

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

and then call the next method in the callback

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

1 回答 1

1

use BehaviorSubject

// 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(...)
于 2021-04-28T07:07:25.863 回答