All Downloads are FREE. Search and download functionalities are using the official Maven repository.

commonMain.hassemble.events.EventHandler.kt Maven / Gradle / Ivy

The newest version!
package hassemble.events

import hassemble.errorHandling.EventHandlerExceptionHandler
import hassemble.observability.Switchable
import kotlinx.atomicfu.atomic

typealias EventHandlerFunction = (EventData, switchable: Switchable) -> Unit

interface EventHandler {
    fun handle(eventData: EventData)
}

internal class EventHandlerImpl(
    private val f: EventHandlerFunction,
    private val exceptionHandler: EventHandlerExceptionHandler
) : EventHandler, Switchable {

    private val enabled = atomic(true)

    override fun enable() { enabled.getAndSet(true) }
    override fun disable() { enabled.getAndSet(false) }
    override fun isEnabled(): Boolean = enabled.value

    override fun handle(eventData: EventData) {
        if (!enabled.value) return
        try {
            f(eventData, this)
        } catch (e: Throwable) {
            exceptionHandler.handleExceptions(e)
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy