home-assistant / home-assistant/android

Introduce CoroutineBroadcastReceiver

Open
#6,000 2 comments 0 reactions 1 assignee Claimed by @TimoPtr View on GitHub
enhancement
Dominant language
Kotlin
Stars
3.9k
Forks
1.1k
Avg merge
1d 12h
Merged PRs (30d)
81

Description

### Description

Most of our `BroadcastReceiver` are using coroutines and all of them are creating a new scope not tight to any lifecycle.
According to the documentation of `BroadcastReceiver` the execution of the `onReceive` method should end within 10s otherwise the system is going to raise an ANR. There is a way to extend this to 30s using `goAsync`, but the app is not using it and we probably shouldn't and try to fit everything under 10s.

A parallel can be made with the `Worker` API Google introduced a `CoroutineWorker`, the difference is that it has a lifecycle. But still we could use this API to help us design an API to help us/standardize how we deal with coroutine in `BroadcastReceiver`.

### Additional context

This has been first discussed in https://github.com/home-assistant/android/pull/5998

A proposal of API could be

```kotlin
abstract class CoroutineBroadcastReceiver : BroadcastReceiver() {
final override fun onReceive(context: Context, intent: Intent) {
GlobalScope.launch {
withTimeout(10.seconds) {
onReceiveIntent(context, intent)
}
}
}

abstract suspend fun onReceiveIntent(context: Context, intent: Intent)
}
```

No need to create a new scope since this new scope would not be tight to any lifecycle.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.