Skip to content

Commit

Permalink
Clean up event emitter listeners
Browse files Browse the repository at this point in the history
  • Loading branch information
yogwoggf committed Apr 27, 2024
1 parent 763bac5 commit f7b5767
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 24 deletions.
24 changes: 24 additions & 0 deletions src/main/kotlin/com/puffy/events/BasicEventListener.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package com.puffy.events

class BasicEventListener<Identifier, EventType> : EventStreamListener<Identifier, EventType> {
private val listeners: MutableMap<Identifier, MutableSet<EventListener<EventType>>> =
mutableMapOf()

override fun register(identifier: Identifier, listener: EventListener<EventType>) {
if (listeners[identifier] == null) {
listeners[identifier] = mutableSetOf()
}

listeners[identifier]?.add(listener)
}

override fun unregister(identifier: Identifier, listener: EventListener<EventType>) {
listeners[identifier]?.remove(listener)
}

fun notifyListeners(event: EventType) {
listeners.forEach { entry ->
entry.value.forEach { eventListener -> eventListener.onEvent(event) }
}
}
}
27 changes: 3 additions & 24 deletions src/main/kotlin/com/puffy/events/DetectionEventEmitter.kt
Original file line number Diff line number Diff line change
Expand Up @@ -5,34 +5,13 @@ import net.minecraft.server.network.ServerPlayerEntity
data class DetectionInfo(val detectionSourceName: String, val player: ServerPlayerEntity)

object DetectionEventEmitter : EventStream<DetectionInfo> {
private object DetectionEventListener : EventStreamListener<String, DetectionInfo> {
private val listeners: MutableMap<String, MutableSet<EventListener<DetectionInfo>>> =
mutableMapOf()

override fun register(identifier: String, listener: EventListener<DetectionInfo>) {
if (listeners[identifier] == null) {
listeners[identifier] = mutableSetOf()
}

listeners[identifier]?.add(listener)
}

override fun unregister(identifier: String, listener: EventListener<DetectionInfo>) {
listeners[identifier]?.remove(listener)
}

fun notifyListeners(event: DetectionInfo) {
listeners.forEach { entry ->
entry.value.forEach { eventListener -> eventListener.onEvent(event) }
}
}
}
private val eventListener = BasicEventListener<String, DetectionInfo>()

override fun sendEvent(event: DetectionInfo) {
DetectionEventListener.notifyListeners(event)
eventListener.notifyListeners(event)
}

fun addListener(identifier: String, listener: EventListener<DetectionInfo>) {
DetectionEventListener.register(identifier, listener)
eventListener.register(identifier, listener)
}
}

0 comments on commit f7b5767

Please sign in to comment.