From d18399795bd9869e9bfeff9b0f51355988ee8b8b Mon Sep 17 00:00:00 2001 From: DBotThePony Date: Sun, 21 Jan 2024 23:33:03 +0700 Subject: [PATCH] Void/Unit subscripable --- .../dbotthepony/mc/otm/core/ISubscripable.kt | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/src/main/kotlin/ru/dbotthepony/mc/otm/core/ISubscripable.kt b/src/main/kotlin/ru/dbotthepony/mc/otm/core/ISubscripable.kt index 5bbd7b52e..75f487e45 100644 --- a/src/main/kotlin/ru/dbotthepony/mc/otm/core/ISubscripable.kt +++ b/src/main/kotlin/ru/dbotthepony/mc/otm/core/ISubscripable.kt @@ -66,6 +66,44 @@ interface ISubscriptable { } } +interface IUnitSubscripable : ISubscriptable { + fun addListener(listener: Runnable): ISubscriptable.L + + override fun addListener(listener: Consumer): ISubscriptable.L { + return addListener(Runnable { listener.accept(Unit) }) + } + + class Impl : IUnitSubscripable, Runnable { + private inner class L(val callback: Runnable) : ISubscriptable.L { + private var isRemoved = false + + init { + subscribers.add(this) + } + + override fun remove() { + if (!isRemoved) { + isRemoved = true + queue.add(this) + } + } + } + + private val subscribers = ReferenceLinkedOpenHashSet(0) + private val queue = ReferenceArraySet(0) + + override fun addListener(listener: Runnable): ISubscriptable.L { + return L(listener) + } + + override fun run() { + queue.forEach { subscribers.remove(it) } + queue.clear() + subscribers.forEach { it.callback.run() } + } + } +} + interface IFloatSubcripable : ISubscriptable { @Deprecated("Use type specific listener") override fun addListener(listener: Consumer): ISubscriptable.L {