Skip to content

Instantly share code, notes, and snippets.

@roschlau
Forked from orangy/event.kt
Last active July 7, 2017 13:32
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save roschlau/b430927d4233b0876618090f00c3110a to your computer and use it in GitHub Desktop.
Save roschlau/b430927d4233b0876618090f00c3110a to your computer and use it in GitHub Desktop.
C#-style events in Kotlin
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
}
@niondir
Copy link

niondir commented Jul 22, 2016

A shorter version that also reduces the visibility problem, at least for code outside of the module:

class Event<TArgs> : ArrayList<(TArgs) -> Unit>() {
    internal operator fun invoke(e: TArgs) = forEach { it(e) }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment