Skip to content

Instantly share code, notes, and snippets.

@duyuxuan
Forked from gpeal/BroadcastReceiver.kt
Created February 20, 2022 13:51
Show Gist options
  • Save duyuxuan/4db6e98e4651ed5c5782019e01b5e1ac to your computer and use it in GitHub Desktop.
Save duyuxuan/4db6e98e4651ed5c5782019e01b5e1ac to your computer and use it in GitHub Desktop.
Coroutine Broadcast Receivers
context.registerReceiverInScope(scope, WifiManager.WIFI_STATE_CHANGED_ACTION) { intent ->
val state = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, WifiManager.WIFI_STATE_DISABLED)
// Use wifi state here
}
/**
* Register a broadcast receiver in the given coroutine scope for any of the specified actions
* and call the callback when it is invoked.
*/
fun Context.registerReceiverInScope(
scope: CoroutineScope,
vararg intentFilterActions: String,
callback: (Intent) -> Unit,
) {
val receiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
callback(intent)
}
}
val intentFilter = IntentFilter()
intentFilterActions.forEach { intentFilter.addAction(it) }
registerReceiver(receiver, intentFilter)
scope.invokeOnCompletion {
unregisterReceiver(receiver)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment