I was wondering how to deal with coroutines cancelation in a BroadcastReceiver. I have to run some suspending methods and for the moment I am using a GlobalScope.launch or a runBlocking. Is there another way in order to control the job that is being fired and cancel when the BroadcastReceiver() is finished? It's an AlarmManager specifically.
For all saying to switch to a WorkManager the answer is no because I'm scheduling work at exact time and WorkManager doesn't do that for you. So in order to set Alarms I have to read some data from a suspend method once the AlarmManager is fired. I also tried this solution:
//inside Alarm Managers onReceive Method
val job = coroutineScope.launch {
delayingOperationMethod()
}
job.invokeOnCompletion {
coroutineScope.cancel()
}
Where job is just:
private val job: Job = Job()
private val coroutineScope = CoroutineScope(job + Dispatchers.IO)
Is this a way of doing it?
Looks like the GlobalScope was the best solution:
GlobalScope.launch(Dispatchers.IO){
///
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With