Skip to content

Instantly share code, notes, and snippets.

@odbol
Last active May 9, 2026 18:14
Show Gist options
  • Select an option

  • Save odbol/dc2bcf67533d2fb5b41429808185813d to your computer and use it in GitHub Desktop.

Select an option

Save odbol/dc2bcf67533d2fb5b41429808185813d to your computer and use it in GitHub Desktop.
Shares events across activities, services, etc. So much simpler than the Java version! But still useful.
package com.odbol.utils
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
/** Shares events across activities, services, etc */
object EventBus {
val events = MutableSharedFlow<Event>(replay = 1, extraBufferCapacity = 8)
}
sealed class Event {
data object OnHelloWorld : Event()
data class OnError(val error: String) : Event()
// Add your own events here...
}
// Example of how to listen to events from an Activity or wherever
fun onCreate() {
lifecycleScope.launch(Dispatchers.IO) {
EventBus.events.collect { event ->
when (event) {
is Event.OnClick -> Log.v(TAG, "Hello, I'm a bus!")
is Event.OnError -> Log.e(TAG, "Error: ${event.error}")
}
}
}
}
// Example on how to send events
fun onClick() {
if (isValid) {
EventBus.events.tryEmit(Event.OnClick)
} else {
EventBus.events.tryEmit(Event.OnError("Invalid click!"))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment