commonMain.hassemble.events.EventHandler.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of hassemble-jvm Show documentation
Show all versions of hassemble-jvm Show documentation
Interact with your Home Assistant server using Kotlin.
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)
}
}
}