Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cancel coroutines in a BroadcastReceiver

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?

like image 951
coroutineDispatcher Avatar asked Nov 05 '19 11:11

coroutineDispatcher


1 Answers

Looks like the GlobalScope was the best solution:

GlobalScope.launch(Dispatchers.IO){
 ///
}
like image 109
coroutineDispatcher Avatar answered Nov 03 '22 04:11

coroutineDispatcher