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) | |
} | |
} |
great minds think alike lol
class EventBus private constructor(val scope: CoroutineScope) {
private val _bus = MutableSharedFlow<T>(replay = 1)
val bus: SharedFlow<T> = _bus.asSharedFlow()
fun post(event: T) {
scope.launch(Dispatchers.IO) {
_bus.emit(event)
}
}
inline fun <reified E : T> subscribe(
dispatcher: CoroutineDispatcher = Dispatchers.Main,
crossinline action: (event: E) -> Unit
): Job {
val job = SupervisorJob(scope.coroutineContext[Job])
return scope.launch(dispatcher + job) {
bus.filterIsInstance<E>().collect {
action(it)
}
}
}
companion object {
private lateinit var instance: EventBus<*>
fun <T> initialize(scope: CoroutineScope): EventBus<T> {
instance = EventBus<T>(scope)
return instance as EventBus<T>
}
@Suppress("UNCHECKED_CAST")
fun <T> get(): EventBus<T> = instance as EventBus<T>
}
}
will this code opt this ?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@ursusursus funny enough, we added this recently as well: