Skip to content

Commit

Permalink
Introduce ListenerInstance, making it possible to unregister listeners
Browse files Browse the repository at this point in the history
  • Loading branch information
jakobkmar committed Jul 23, 2022
1 parent 242681f commit 802e7d4
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 6 deletions.
23 changes: 17 additions & 6 deletions silk-core/src/main/kotlin/net/silkmc/silk/core/event/Event.kt
Original file line number Diff line number Diff line change
Expand Up @@ -52,20 +52,31 @@ open class Event<T, S : EventScope>(val scopeSupplier: () -> S) {
* @param priority specifies the priority with which this listener will be called
* over the other listeners, see [EventPriority] - for listeners which should be
* invoked synchronously after all mutations have taken place, see [monitor]
* @param register if true (the default), the listener will be register immediately
*
* @return the [ListenerInstance], making it possible to register and unregister
* the listener later
*/
fun listen(priority: EventPriority = EventPriority.NORMAL, callback: context(S, MutableEventScope) (T) -> Unit) {
synchronized(this) {
listenersByPriority[priority.ordinal].add(callback)
}
fun listen(
priority: EventPriority = EventPriority.NORMAL,
register: Boolean = true,
callback: context(S, MutableEventScope) (T) -> Unit,
): ListenerInstance<*> {
return ListenerInstance(this, callback, listenersByPriority[priority.ordinal])
.also { if (register) it.register() }
}

/**
* Monitors this event. This is the same as [listen], but you do not have access
* to the mutable functions of the event scope. This [callback] will be executed
* **after** [EventPriority.LAST], therefore monitor sees the final state.
*/
fun monitor(callback: context(S) (T) -> Unit) {
monitorListeners.add(callback)
fun monitor(
register: Boolean = true,
callback: context(S) (T) -> Unit,
): ListenerInstance<*> {
return ListenerInstance(this, callback, monitorListeners)
.also { if (register) it.register() }
}

/**
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package net.silkmc.silk.core.event

/**
* A simple instance class keeping track of a registered listener
* and making it possible to unregister it later.
*/
class ListenerInstance<L>(
private val lock: Any,
private val listener: L,
private val list: MutableList<L>,
) {

private var registered = false

/**
* Unregisters this listener, meaning that it won't be called for
* new event invocations in the future.
*/
fun unregister() {
synchronized(lock) {
if (registered) {
registered = false
list.remove(listener)
}
}
}

/**
* Tries to register this listener, if it is not already registered.
*/
fun register() {
synchronized(lock) {
if (!registered) {
registered = true
list.add(listener)
}
}
}
}

0 comments on commit 802e7d4

Please sign in to comment.