【问题标题】:Return a Deferred type from Polidea bluetooth library - Kotlin Coroutines从 Polidea 蓝牙库返回延迟类型 - Kotlin Coroutines
【发布时间】:2019-06-10 07:05:25
【问题描述】:

我正在用 kotlin 协程做一些实验,特别是我想从polidea 库返回我的协程一个 RxBleDevice。 但是,Polidea scanBleDevices 函数在订阅时返回 Disposable。根据我的代码,有什么方法可以将 RxBleDevice 返回到我的协程?

这是我的代码,目前无法编译:

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

【问题讨论】:

标签: android kotlin bluetooth-lowenergy kotlinx.coroutines


【解决方案1】:

您需要将subscribe 方法调用包装到

suspendCancellableCoroutine< RxBleDevice>{ cont ->
  //your code here
}

块。在subscribe 回调实现中,使用cont.resume() 恢复协程并返回结果,使用cont.resumeWithException 恢复协程并出现错误。

您可能还想在协程和扫描活动之间绑定取消。详情请见cont.invokeOnCancellation { }

您调用的 API 看起来像一个 Rx,也许这些模块之一有帮助 https://github.com/Kotlin/kotlinx.coroutines/blob/master/reactive/README.md

【讨论】:

  • 谢谢,它有效!你认为扩展功能也可以是一种方式吗?
  • 是的,我想是的。或者您可以创建自己的扩展函数来执行 subscribe 并在内部暂停以使代码更易于阅读
猜你喜欢
  • 2012-03-27
  • 1970-01-01
  • 2015-01-09
  • 2019-03-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多