kotlinforandroid
06/21/2022, 11:50 AMandroidx.work.Worker . However, reading the value requires me to register a callback. How do I make my worker wait for the callback to return once without using a busy-loop? Is there a builtin way? JobService has a dedicated finishJob method that one could call from the callback. androidx.work seems to not have this
class MyWorker(sm: SensorManager, sensor: Sensor, context: Context, params: WorkerParameter): Worker(context, params) {
private flag: Boolean = false
override fun doWork(): Result {
sm.registerListener(object : SensorEventListener {
override fun onSensorEvent(e: SensorEvent) {
flag = true
// use value...
}
}, sensor, TIMEFRAME_FASTEST)
while (!flag) { }
return Result.success()
}
}Adam Powell
06/21/2022, 1:28 PMCoroutineWorker you can use suspending to do itkotlinforandroid
06/21/2022, 1:48 PMCoroutineContext. Could you further elaborate on your suggestion? Maybe showing a code snippet on how you would use CoroutineWorker .Casey Brooks
06/21/2022, 2:37 PMsuspendCancellableCoroutine is the bridge between the callback-based registerListener and coroutines
So you’d end up with a doWork() function like this:
override suspend fun doWork(): Result {
return suspendCancellableCoroutine { continuation ->
sm.registerListener(object : SensorEventListener {
override fun onSensorEvent(e: SensorEvent) {
// use value...
continuation.resume(Result.success())
}
}, sensor, TIMEFRAME_FASTEST)
}
}kotlinforandroid
06/21/2022, 3:42 PMAdam Powell
06/21/2022, 7:24 PMcallbackFlow {} or similar. I'd assume that the above snippet verbatim with suspendCancellableCoroutine would still leave the listener registered; whatever solution you go with should account for cleaning that upgildor
06/22/2022, 3:42 AM