Created
June 23, 2021 15:04
-
-
Save zihadmahiuddin/0f550f5cf95e81390e9b3e0b824f4d46 to your computer and use it in GitHub Desktop.
Simple Event Emitter for Kotlin
This file contains 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
package dev.zihad.util | |
interface Event |
This file contains 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
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) | |
} | |
} |
This file contains 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
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