Certainly! Below is a robust implementation of an EventManager class in Kotlin for Android, meeting all your requirements:
Kotlin Coroutines & Flow: Uses MutableSharedFlow for event publishing and subscription.
Lifecycle Awareness: Observers are only active when the LifecycleOwner is at least STARTED, using lifecycleScope and repeatOnLifecycle.
Thread Safety: SharedFlow is thread-safe and supports concurrent emissions and collections.
Tag Filtering: Each event can have an optional tag for filtering.
Memory Efficiency: No strong references to Context or observers; uses weak references via LifecycleOwner and coroutines.
API: post, observe, and observeAll methods.
kotlin
import androidx.lifecycle.*
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
import java.util.concurrent.atomic.AtomicReference
/**
* EventManager enables sending and observing events across the app.
*/
class EventManager<T : Any> private constructor() {
private data class Event<T>(val value: T, val tag: String?)
// SharedFlow for events, no replay, unbounded buffer for bursty events
private val _events = MutableSharedFlow<Event<T>>(
replay = 0,
extraBufferCapacity = 64,
onBufferOverflow = BufferOverflow.DROP_OLDEST
)
/**
* Post an event with an optional tag.
*/
fun post(event: T, tag: String? = null) {
// Use tryEmit for non-blocking emission
_events.tryEmit(Event(event, tag))
}
/**
* Observe events with a specific tag.
* Only receives events when the LifecycleOwner is at least STARTED.
*/
fun observe(
lifecycleOwner: LifecycleOwner,
tag: String,
onEvent: (T) -> Unit
) {
observeInternal(lifecycleOwner, tag, onEvent)
}
/**
* Observe all events, regardless of tag.
* Only receives events when the LifecycleOwner is at least STARTED.
*/
fun observeAll(
lifecycleOwner: LifecycleOwner,
onEvent: (T, tag: String?) -> Unit
) {
observeInternal(lifecycleOwner, null) { event, tag ->
onEvent(event, tag)
}
}
// Internal observe function
private fun observeInternal(
lifecycleOwner: LifecycleOwner,
tag: String?,
onEvent: (T, String?) -> Unit
) {
lifecycleOwner.lifecycleScope.launch {
lifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
_events
.filter { tag == null || it.tag == tag }
.collect { event ->
onEvent(event.value, event.tag)
}
}
}
}
companion object {
// Singleton instance for each event type
private val instances = mutableMapOf<Class<*>, Any>()
@Suppress("UNCHECKED_CAST")
fun <T : Any> getInstance(eventClass: Class<T>): EventManager<T> {
return instances.getOrPut(eventClass) { EventManager<T>() } as EventManager<T>
}
}
}
Usage Example
Suppose you have an event class:
kotlin
data class MyEvent(val message: String)
Posting an event:
kotlin
EventManager.getInstance(MyEvent::class.java).post(MyEvent("Hello!"), tag = "greeting")