Last active
February 28, 2025 12:34
-
-
Save gpeal/1c86aa3aacc1c26724e0d76f0023594e to your computer and use it in GitHub Desktop.
Coroutine Broadcast Receivers
This file contains hidden or 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
class EventBus private constructor(val scope: CoroutineScope) {
}
will this code opt this ?