Design a Kotlin class for Android named EventManager that enables sending and observing…
- User
Design a Kotlin class for Android named
EventManagerthat enables sending and observing events across different parts of the application.Requirements:
- Use Kotlin Coroutines and Flow for event publishing and subscription.
- Ensure strict and proper Lifecycle management for observers (e.g., only active when the LifecycleOwner is at least STARTED).
- The class must be thread-safe and support concurrent event handling without synchronization issues.
- Each event can have an optional
tagstring to allow more precise event filtering and identification. - The implementation must avoid memory leaks and be memory-efficient. No strong references to context or observers should be retained.
- The class must provide the following methods:
- post
- observe
- observeAll
Assistant
Here's a comprehensive
EventManagerimplementation that meets all your requirements:import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.lifecycleScope import androidx.lifecycle.repeatOnLifecycle import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.asSharedFlow import kotlinx.coroutines.flow.filter import kotlinx.coroutines.flow.receiveAsFlow import kotlinx.coroutines.launch import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import java.lang.ref.WeakReference import java.util.concurrent.ConcurrentHashMap /** * Thread-safe EventManager for Android applications using Kotlin Coroutines and Flow. * Provides lifecycle-aware event publishing and subscription with memory leak prevention. */ class EventManager { /** * Data class representing an event with optional tag for filtering */ data class Event<T>( val data: T, val tag: String? = null, val timestamp: Long = System.currentTimeMillis() ) // Thread-safe shared flow for broadcasting events private val _eventFlow = MutableSharedFlow<Event<Any>>( replay = 0, extraBufferCapacity = Channel.UNLIMITED ) private val eventFlow = _eventFlow.asSharedFlow() // Thread-safe map to track active observers for cleanup private val activeObservers = ConcurrentHashMap<String, WeakReference<LifecycleOwner>>() private val observerMutex = Mutex() /** * Posts an event to all subscribers * * @param data The event data to broadcast * @param tag Optional tag for event filtering */ suspend fun <T> post(data: T, tag: String? = null) { val event = Event(data as Any, tag) _eventFlow.emit(event) } /** * Posts an event synchronously (non-suspending) * * @param data The event data to broadcast * @param tag Optional tag for event filtering */ fun <T> postSync(data: T, tag: String? = null) { val event = Event(data as Any, tag) _eventFlow.tryEmit(event) } /** * Observes events of a specific type with optional tag filtering * Automatically manages lifecycle and prevents memory leaks * * @param lifecycleOwner The lifecycle owner for automatic cleanup * @param tag Optional tag to filter events (null means no tag filtering) * @param eventClass The class type of events to observe * @param observer The callback function to handle events */ inline fun <reified T> observe( lifecycleOwner: LifecycleOwner, tag: String? = null, crossinline observer: suspend (T) -> Unit ) { val observerId = generateObserverId(lifecycleOwner, T::class.java.simpleName, tag) lifecycleOwner.lifecycleScope.launch { // Register observer for cleanup tracking observerMutex.withLock { activeObservers[observerId] = WeakReference(lifecycleOwner) } try { lifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) { eventFlow .filter { event -> // Filter by type event.data is T && // Filter by tag if specified (tag == null || event.tag == tag) } .collect { event -> @Suppress("UNCHECKED_CAST") observer(event.data as T) } } } finally { // Clean up observer reference observerMutex.withLock { activeObservers.remove(observerId) } } } } /** * Observes all events regardless of type with optional tag filtering * Automatically manages lifecycle and prevents memory leaks * * @param lifecycleOwner The lifecycle owner for automatic cleanup * @param tag Optional tag to filter events (null means no tag filtering) * @param observer The callback function to handle events */ fun observeAll( lifecycleOwner: LifecycleOwner, tag: String? = null, observer: suspend (Event<Any>) -> Unit ) { val observerId = generateObserverId(lifecycleOwner, "ALL", tag) lifecycleOwner.lifecycleScope.launch { // Register observer for cleanup tracking observerMutex.withLock { activeObservers[observerId] = WeakReference(lifecycleOwner) } try { lifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) { eventFlow .filter { event -> // Filter by tag if specified tag == null || event.tag == tag } .collect { event -> observer(event) } } } finally { // Clean up observer reference observerMutex.withLock { activeObservers.remove(observerId) } } } } /** * Returns a Flow for manual subscription (advanced usage) * Note: Manual lifecycle management required when using this method * * @param tag Optional tag to filter events * @return Flow of filtered events */ inline fun <reified T> getEventFlow(tag: String? = null): Flow<T> { return eventFlow .filter { event -> event.data is T && (tag == null || event.tag == tag) } .filter { it.data is T } .map { @Suppress("UNCHECKED_CAST") it.data as T } } /** * Returns a Flow for all events with optional tag filtering * Note: Manual lifecycle management required when using this method * * @param tag Optional tag to filter events * @return Flow of filtered events */ fun getAllEventFlow(tag: String? = null): Flow<Event<Any>> { return eventFlow.filter { event -> tag == null || event.tag == tag } } /** * Cleans up dead observer references * Called automatically but can be invoked manually for immediate cleanup */ suspend fun cleanupDeadObservers() { observerMutex.withLock { val deadObservers = activeObservers.filterValues { ref -> ref.get() == null }.keys deadObservers.forEach { observerId -> activeObservers.remove(observerId) } } } /** * Gets the current number of active observers (for debugging/monitoring) */ suspend fun getActiveObserverCount(): Int { cleanupDeadObservers() return observerMutex.withLock { activeObservers.size } } /** * Generates a unique observer ID for tracking */ private fun generateObserverId( lifecycleOwner: LifecycleOwner, eventType: String, tag: String? ): String { return "${lifecycleOwner.hashCode()}_${eventType}_${tag ?: "notag"}_${System.nanoTime()}" } companion object { /** * Singleton instance for global event management * Use this for application-wide events */ @Volatile private var INSTANCE: EventManager? = null fun getInstance(): EventManager { return INSTANCE ?: synchronized(this) { INSTANCE ?: EventManager().also { INSTANCE = it } } } } } // Extension functions for easier usage /** * Extension function to post events more conveniently */ suspend fun <T> EventManager.postEvent(data: T, tag: String? = null) { post(data, tag) } /** * Extension function to post events synchronously */ fun <T> EventManager.postEventSync(data: T, tag: String? = null) { postSync(data, tag) }Here's how to use the
EventManager:// Example usage in an Activity or Fragment class MainActivity : AppCompatActivity() { private val eventManager = EventManager.getInstance() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // Observe specific event types with tags eventManager.observe<String>(this, tag = "user_action") { message -> // Handle string events with "user_action" tag showToast(message) } // Observe all events with a specific tag eventManager.observeAll(this, tag = "analytics") { event -> // Handle all analytics events logAnalyticsEvent(event.data, event.tag, event.timestamp) } // Observe specific data class events eventManager.observe<UserLoginEvent>(this) { loginEvent -> // Handle user login events updateUI(loginEvent.user) } } private fun onButtonClick() { lifecycleScope.launch { // Post events eventManager.post("User clicked button", tag = "user_action") eventManager.post(UserLoginEvent(User("John")), tag = "analytics") } } } // Example data classes for events data class UserLoginEvent(val user: User) data class User(val name: String)Key Features:
-
Coroutines & Flow: Uses
MutableSharedFlowfor thread-safe event broadcasting with unlimited buffer capacity. -
Lifecycle Management: Uses
repeatOnLifecycle(Lifecycle.State.STARTED)to ensure observers only receive events when active. -
Thread Safety: Employs
ConcurrentHashMapandMutexfor thread-safe operations without blocking. -
Tag Support: Events can have optional tags for precise filtering.
-
Memory Leak Prevention: Uses
WeakReferencefor observer tracking and automatic cleanup when lifecycle owners are destroyed. -
Memory Efficiency: No replay buffer, automatic cleanup of dead observers, and proper resource management.
The implementation provides both high-level convenience methods (
observe,observeAll) and low-level access (getEventFlow) for advanced use cases, while maintaining strict lifecycle awareness and memory safety.-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.