-
Notifications
You must be signed in to change notification settings - Fork 14
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Introduce
ListenerInstance
, making it possible to unregister listeners
- Loading branch information
Showing
2 changed files
with
56 additions
and
6 deletions.
There are no files selected for viewing
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
39 changes: 39 additions & 0 deletions
39
silk-core/src/main/kotlin/net/silkmc/silk/core/event/ListenerInstance.kt
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
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) | ||
} | ||
} | ||
} | ||
} |