-
-
Save roschlau/b430927d4233b0876618090f00c3110a to your computer and use it in GitHub Desktop.
C#-style events in Kotlin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Event<T> { | |
private val handlers = arrayListOf<(T) -> Unit>() | |
operator fun plusAssign(handler: (T) -> Unit) { handlers.add(handler) } | |
operator fun invoke(value: T) { for (handler in handlers) handler(value) } | |
} | |
val e = Event<String>() // define event | |
fun main(args : Array<String>) { | |
e += { println(it) } // subscribe | |
e("sdfsdf") // invoke | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A shorter version that also reduces the visibility problem, at least for code outside of the module: