Abhimanyu
06/22/2024, 1:21 PMViewModel
(AAC) , we have viewModelScope
- A CloseableCoroutineScope
tied to the ViewModel lifecycle.
Do we have any such CloseableCoroutineScope
for BroadcastReceiver()
?Chrimaeon
06/22/2024, 1:44 PMBecause a receiver’shttps://developer.android.com/develop/background-work/background-tasks/broadcasts#security-and-best-practicesmethod runs on the main thread, it should execute and return quickly. If you need to perform long running work, be careful about spawning threads or starting background services because the system can kill the entire process afteronReceive(Context, Intent)
returns. For more information, see Effect on process state To perform long running work, we recommend:onReceive()
Abhimanyu
06/22/2024, 1:46 PMChrimaeon
06/22/2024, 1:48 PMrunBlocking
then and stay on the main thread.Chrimaeon
06/22/2024, 1:50 PMAbhimanyu
06/22/2024, 1:50 PMval coroutineScope = MainScope() + job
Just a bit not sure to use runBlocking
.Chrimaeon
06/22/2024, 1:51 PM```* Runs a new coroutine and blocks the current thread interruptibly until its completion.
*
* It is designed to bridge regular blocking code to libraries that are written in suspending style, to be used in
*functions and in tests.```main
Chrimaeon
06/22/2024, 1:52 PMonReceive
complete before your suspend function returns.Abhimanyu
06/22/2024, 1:54 PMonReceive
can complete before the coroutine completes 🤔 ?
@AndroidEntryPoint
public class TimeChangedReceiver : BroadcastReceiver() {
private val job = Job()
private val coroutineScope = MainScope() + job
@Inject
public lateinit var alarmKit: AlarmKit
override fun onReceive(
context: Context?,
intent: Intent?,
) {
if (intent?.action == "android.intent.action.TIME_SET") {
coroutineScope.launch {
doWork()
cleanUp()
}
}
}
private suspend fun doWork() {
alarmKit.enableReminder()
}
private fun cleanUp() {
job.cancel()
}
}
Chrimaeon
06/22/2024, 1:56 PMChrimaeon
06/22/2024, 1:57 PMlaunch
call your function will return.Abhimanyu
06/22/2024, 1:57 PMChrimaeon
06/22/2024, 2:01 PMlaunch
call your function will return and is free for getting killed by the system.Abhimanyu
06/22/2024, 2:02 PMrunBlocking
is the only proper solution for this?
Also, anything else wrong with the code?Chrimaeon
06/22/2024, 2:03 PMoverride fun onReceive(
context: Context?,
intent: Intent?,
) {
if (intent?.action == "android.intent.action.TIME_SET") {
runBlocking {
doWork()
}
}
}
should be all you need.Chrimaeon
06/22/2024, 2:06 PMandroidx.lifecycle.LifecycleService
which handles the scope as cancelation properly.Abhimanyu
06/22/2024, 2:08 PMrunBlocking
for now.
I will switch to service if required later.
thank you color