Add per compat project event listeners
[no changelog]
This commit is contained in:
@@ -1,8 +1,7 @@
|
||||
|
||||
|
||||
package moe.nea.firmament.events
|
||||
|
||||
import java.util.concurrent.CopyOnWriteArrayList
|
||||
import org.apache.commons.lang3.reflect.TypeUtils
|
||||
import moe.nea.firmament.Firmament
|
||||
import moe.nea.firmament.util.MC
|
||||
|
||||
@@ -13,18 +12,31 @@ import moe.nea.firmament.util.MC
|
||||
* Subscriptions may not necessarily be delivered in the order of registering.
|
||||
*/
|
||||
open class FirmamentEventBus<T : FirmamentEvent> {
|
||||
companion object {
|
||||
val allEventBuses = mutableListOf<FirmamentEventBus<*>>()
|
||||
}
|
||||
|
||||
val eventType = TypeUtils.getTypeArguments(javaClass, FirmamentEventBus::class.java)!!.values.single()
|
||||
|
||||
init {
|
||||
allEventBuses.add(this)
|
||||
}
|
||||
|
||||
data class Handler<T>(
|
||||
val invocation: (T) -> Unit, val receivesCancelled: Boolean,
|
||||
var knownErrors: MutableSet<Class<*>> = mutableSetOf(),
|
||||
val label: String,
|
||||
)
|
||||
|
||||
private val toHandle: MutableList<Handler<T>> = CopyOnWriteArrayList()
|
||||
fun subscribe(handle: (T) -> Unit) {
|
||||
subscribe(false, handle)
|
||||
val handlers: List<Handler<T>> get() = toHandle
|
||||
|
||||
fun subscribe(label: String, handle: (T) -> Unit) {
|
||||
subscribe(false, label, handle)
|
||||
}
|
||||
|
||||
fun subscribe(receivesCancelled: Boolean, handle: (T) -> Unit) {
|
||||
toHandle.add(Handler(handle, receivesCancelled))
|
||||
fun subscribe(receivesCancelled: Boolean, label: String, handle: (T) -> Unit) {
|
||||
toHandle.add(Handler(handle, receivesCancelled, label = label))
|
||||
}
|
||||
|
||||
fun publish(event: T): T {
|
||||
|
||||
@@ -13,4 +13,5 @@ data class Subscription<T : FirmamentEvent>(
|
||||
val owner: Any,
|
||||
val invoke: (T) -> Unit,
|
||||
val eventBus: FirmamentEventBus<T>,
|
||||
val methodName: String,
|
||||
)
|
||||
|
||||
25
src/main/kotlin/events/subscription/SubscriptionList.kt
Normal file
25
src/main/kotlin/events/subscription/SubscriptionList.kt
Normal file
@@ -0,0 +1,25 @@
|
||||
package moe.nea.firmament.events.subscription
|
||||
|
||||
import java.util.ServiceLoader
|
||||
import kotlin.streams.asSequence
|
||||
import moe.nea.firmament.Firmament
|
||||
|
||||
interface SubscriptionList {
|
||||
fun provideSubscriptions(addSubscription: (Subscription<*>) -> Unit)
|
||||
|
||||
companion object {
|
||||
val allLists by lazy {
|
||||
ServiceLoader.load(SubscriptionList::class.java)
|
||||
.stream()
|
||||
.asSequence()
|
||||
.mapNotNull {
|
||||
kotlin.runCatching { it.get() }
|
||||
.getOrElse { ex ->
|
||||
Firmament.logger.error("Could not load subscriptions from ${it.type()}", ex)
|
||||
null
|
||||
}
|
||||
}
|
||||
.toList()
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user