Skip to content

Instantly share code, notes, and snippets.

@hrules6872
Created January 18, 2018 15:13
Show Gist options
  • Save hrules6872/b8f0f01d8205a7c4d3e7c7e8cf5d99f4 to your computer and use it in GitHub Desktop.
Save hrules6872/b8f0f01d8205a7c4d3e7c7e8cf5d99f4 to your computer and use it in GitHub Desktop.
Simple Event Bus Kotlin
object Bus {
// val event = Event<Any>()
}
class Event<TYPE> {
private val handlers = arrayListOf<((TYPE) -> Unit)>()
operator fun plusAssign(handler: (TYPE) -> Unit) {
handlers.add(handler)
}
operator fun minusAssign(handler: (TYPE) -> Unit) {
handlers.remove(handler)
}
operator fun invoke(type: TYPE) = handlers.toList().forEach { it(type) }
}
@hrules6872
Copy link
Author

Example:

Bus {
  val event = Event<Model>()
}
private val event: (Model) -> Unit = { 
  // whatever 
}

fun bind() {
  Bus.event += event
}

fun unbind() {
  Bus.event -= event
}

Bus.event(Model())

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