-
-
Save duyuxuan/4db6e98e4651ed5c5782019e01b5e1ac to your computer and use it in GitHub Desktop.
Coroutine Broadcast Receivers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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