spierce7
02/21/2019, 4:36 PMCoroutineStart.ATOMIC
does? The documentation isn't very clear to me.ansman
02/21/2019, 4:41 PMval job = launch { /* Will never run */ }
job.cancel()
vs
val job = launch(start = ATOMIC) {
/* Will run but isCancelled will be true */
}
job.cancel()
spierce7
02/21/2019, 4:55 PMuli
02/21/2019, 4:56 PMansman
02/21/2019, 4:56 PMuli
02/21/2019, 5:02 PMfun ring(context: Context) {
val pm = context.powerManager
val wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "AlarmHandover")
wakeLock.acquire()
// Launch coroutine ATOMIC to make sure at least the finally block is executed and can release the wake lock
GlobalScope.launch(Dispatchers.Main, CoroutineStart.ATOMIC) {
try {
/// Start ringing an alarm.
} finally {
wakeLock.release()
}
}
}
In this case, I need to acquire a wake lock before launching a coroutine, because otherwise the device will go right back to sleep, after I return from ring().
If then the launched coroutine get's canceled, before it enters the try clause, the wake lock would never be released.spierce7
02/21/2019, 5:25 PMuli
02/21/2019, 6:21 PMansman
02/21/2019, 6:22 PM