I'm doing some experiments with kotlin coroutines, in particular I would like to return to my coroutine a RxBleDevice from polidea library. However, Polidea scanBleDevices function returns a Disposable on subscribe. Is there any way, according to my code, to return to my Coroutine a RxBleDevice?
This is my code, at the moment it doesn't compile:
val scanDevices: Deferred<RxBleDevice> = GlobalScope.async {
rxBleClient.scanBleDevices(ScanSettings.Builder()
.build(), filterBuilder.setDeviceName(bikeBleName).build())
.subscribe(
{ scanResult ->
// Process scan result here.
scanResult.bleDevice
},
{ throwable ->
// Handle an error here.
}
)
}
You need to wrap the subscribe
method call into the
suspendCancellableCoroutine< RxBleDevice>{ cont ->
//your code here
}
block. In the subscribe
callback implementation use cont.resume()
to resume coroutine with result and cont.resumeWithException
to resume it with an error.
You may also want to bind cancellation between your coroutine and the scan activity. See cont.invokeOnCancellation { }
for details.
The API you call looks like an Rx, maybe one of these modules help https://github.com/Kotlin/kotlinx.coroutines/blob/master/reactive/README.md