Skip to content

Instantly share code, notes, and snippets.

@zihadmahiuddin
Created June 23, 2021 15:04
Show Gist options
  • Save zihadmahiuddin/0f550f5cf95e81390e9b3e0b824f4d46 to your computer and use it in GitHub Desktop.
Save zihadmahiuddin/0f550f5cf95e81390e9b3e0b824f4d46 to your computer and use it in GitHub Desktop.
Simple Event Emitter for Kotlin
package dev.zihad.util
interface Event
package dev.zihad.util
import dev.zihad.sharedsharder.api.Event
import dev.zihad.sharedsharder.api.EventListener
import kotlin.reflect.KClass
open class EventEmitter {
val listeners = mutableMapOf<KClass<out Event>, MutableList<EventListener<out Event>>>()
fun <E : Event> emit(event: E) {
listeners[event::class]?.filterIsInstance<EventListener<E>>()?.forEach { it.onEvent(event) }
}
inline fun <reified E : Event> on(listener: EventListener<E>) {
val eventListeners = listeners.getOrPut(E::class) {
mutableListOf()
}
eventListeners.add(listener)
}
}
package dev.zihad.util
fun interface EventListener<E: Event> {
fun onEvent(event: E)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment