【发布时间】:2019-07-20 23:39:21
【问题描述】:
我正在尝试实现 CoroutineWorker 以在 Android 应用中执行一些后台工作。我正在使用的第三方库使用 onConnected、onChanged 等回调。如何在 CoroutineWorker 中使用此库?
这是我目前所拥有的
override suspend fun doWork(): Result {
return try {
val appContext = applicationContext
var mReporter: StepCountReporter?
val mStepCountObserver = object : StepCountReporter.StepCountObserver {
override fun onChanged(count: Int) {
Log.d(APP_TAG, "Step reported : $count")
// This is where the work is completed
}
}
val mConnectionListener = object : HealthDataStore.ConnectionListener {
override fun onConnected() {
Log.d(APP_TAG, "Health data service is connected.")
mReporter = StepCountReporter(mStore!!)
if (isPermissionAcquired) {
mReporter!!.start(mStepCountObserver)
} else {
Log.e(APP_TAG, "permissions not acquired")
}
}
override fun onConnectionFailed(error: HealthConnectionErrorResult) {
Log.d(APP_TAG, "Health data service is not available.")
}
override fun onDisconnected() {
Log.d(APP_TAG, "Health data service is disconnected.")
}
}
mStore = HealthDataStore(appContext, mConnectionListener)
mStore!!.connectService()
// wait for mStepCountObserver.onChanged to be called
} catch (error: Throwable) {
Result.failure()
}
}
我正在尝试完成 mStepCountObserver.onChanged 中的协程,但看起来我应该在函数结束时调用 Result.success。
【问题讨论】:
-
尝试
suspendCoroutine或suspendCancellableCoroutine:jacquessmuts.github.io/post/callback_hell 这是有人使用suspendCancellableCoroutine为OkHttp 提供suspend变体的地方:github.com/gildor/kotlin-coroutines-okhttp/blob/master/src/main/… -
除了 @CommonsWare 所说的,你可以参考 Roman 的演讲 youtu.be/YrrUCSi72E8?t=829,它展示了如何在 Kotlin 协程中集成回调样式库。
标签: android kotlin kotlin-coroutines