Skip to content

Commit

Permalink
eventlib: Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
Com6235 committed Jul 8, 2024
1 parent 4691588 commit 7a1c8a8
Show file tree
Hide file tree
Showing 4 changed files with 64 additions and 1 deletion.
2 changes: 2 additions & 0 deletions eventlib/build.gradle.kts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
group = "io.github.com6235"
version = "1.0-SNAPSHOT"
13 changes: 13 additions & 0 deletions eventlib/src/main/kotlin/Event.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package io.github.com6235.eventlib

open class Event<IN : Any> {
protected val listeners = mutableListOf<(IN?) -> Unit>()

operator fun invoke(args: IN) = listeners.forEach { it(args) }

operator fun invoke() = listeners.forEach { it(null) }

operator fun plusAssign(func: (IN?) -> Unit) {
listeners.add(func)
}
}
48 changes: 48 additions & 0 deletions eventlib/src/test/kotlin/EventTest.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import io.github.com6235.eventlib.Event
import org.junit.jupiter.api.Test
import kotlin.test.assertEquals

class EventTest {
@Test
fun invokeTest() {
val event = Event<String>()
val array = arrayOf<Any?>(null, null)
event += {
array[0] = it!!.firstOrNull()
}
event += {
array[1] = it!!.lastOrNull()
}
event("fire")
assertEquals('f', array[0])
assertEquals('e', array[1])
}

data class EventArgs(val old: Int, val new: Int)

val changeEvent = Event<EventArgs>()
private var _value = 0
var value: Int
get() = _value
set(i) {
changeEvent(EventArgs(_value, i))
_value = i
}

@Test
fun test2() {
val oldVals = mutableMapOf<Int, Int>()
changeEvent += {
val args = it!!
oldVals[args.new] = args.old
}
value = 21
value = 15
value = 99
value = 69
assertEquals(0, oldVals[21])
assertEquals(21, oldVals[15])
assertEquals(15, oldVals[99])
assertEquals(99, oldVals[69])
}
}
2 changes: 1 addition & 1 deletion settings.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@ plugins {
id("org.gradle.toolchains.foojay-resolver-convention") version "0.5.0"
}
rootProject.name = "maven-libs"
include("tgbotter", "configurator")
include("tgbotter", "configurator", "eventlib")

0 comments on commit 7a1c8a8

Please sign in to comment.