@@ -5,7 +5,9 @@ import com.lambda.event.Event
55import com.lambda.event.EventFlow
66import com.lambda.event.Muteable
77import com.lambda.event.listener.SafeListener.Companion.concurrentListener
8+ import com.lambda.event.listener.SafeListener.Companion.listenOnce
89import com.lambda.event.listener.SafeListener.Companion.listener
10+ import com.lambda.util.selfReference
911
1012/* *
1113 * An [UnsafeListener] is a specialized type of [Listener] that operates without a [SafeContext].
@@ -79,6 +81,50 @@ class UnsafeListener(
7981 return listener
8082 }
8183
84+ /* *
85+ * Registers a new [UnsafeListener] for a generic [Event] type [T].
86+ * The [function] is executed only once when the [Event] is dispatched.
87+ * This function should only be used when the [function] performs read actions on the game data.
88+ * For only in-game related contexts, use the [SafeListener.listenOnce] function instead.
89+ * The listener will be automatically unsubscribed after the first execution.
90+ * This function is useful for one-time event handling.
91+ *
92+ * Usage:
93+ * ```kotlin
94+ * unsafeListenOnce<MyEvent> { event ->
95+ * println("Unsafe event received only once: $event")
96+ * }
97+ *
98+ * unsafeListenOnce<MyEvent>(priority = 1) { event ->
99+ * println("Unsafe event received only once before the previous listener: $event")
100+ * }
101+ * ```
102+ *
103+ * After the [function] is executed once, the [SafeListener] will be automatically unsubscribed.
104+ *
105+ * @param T The type of the event to listen for. This should be a subclass of Event.
106+ * @param priority The priority of the listener. Listeners with higher priority will be executed first. The Default value is 0.
107+ * @param alwaysListen If true, the listener will be executed even if it is muted. The Default value is false.
108+ * @param function The function to be executed when the event is posted. This function should take an event of type T as a parameter.
109+ * @return The newly created and registered [UnsafeListener].
110+ */
111+ inline fun <reified T : Event > Any.unsafeListenOnce (
112+ priority : Int = 0,
113+ alwaysListen : Boolean = false,
114+ noinline function : (T ) -> Unit ,
115+ ): UnsafeListener {
116+ val destroyable by selfReference<UnsafeListener > {
117+ UnsafeListener (priority, this @unsafeListenOnce, alwaysListen) { event ->
118+ function(event as T )
119+ EventFlow .syncListeners.unsubscribe(self)
120+ }
121+ }
122+
123+ EventFlow .syncListeners.subscribe<T >(destroyable)
124+
125+ return destroyable
126+ }
127+
82128 /* *
83129 * Registers a new [UnsafeListener] for a generic [Event] type [T].
84130 * The [function] is executed on a new thread running asynchronously to the game thread.
0 commit comments