Skip to content

Instantly share code, notes, and snippets.

@tompee26
Created May 1, 2018 09:16
Show Gist options
  • Select an option

  • Save tompee26/d3e7b876ec426c0ad83ed248fc16d629 to your computer and use it in GitHub Desktop.

Select an option

Save tompee26/d3e7b876ec426c0ad83ed248fc16d629 to your computer and use it in GitHub Desktop.
Event aggregator
class EventAggregator {
companion object {
private var singleton: EventAggregator? = null
fun getInstance(): EventAggregator {
if (singleton == null) {
singleton = EventAggregator()
}
return singleton!!
}
}
val subscriptions = ConcurrentHashMap<Any, MutableList<Any>>()
inline fun <reified T : Event> publish(message: T) {
val subscribers = subscriptions[T::class.java]
subscribers?.apply {
this.forEach {
val function = it as (T) -> Unit
function.invoke(message)
}
}
}
inline fun <reified T : Event> subscribe(noinline action: (arg : T) -> Unit) {
val subscribers = subscriptions.getOrPut(T::class.java, { mutableListOf()})
subscribers?.add(action)
}
inline fun <reified T : Event> unsubscribe(noinline action: (arg : T) -> Unit) {
val subscribers = subscriptions[T::class.java]
subscribers?.apply {
if (this.isNotEmpty()) {
subscribers.remove(action)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment