Created
May 1, 2018 09:16
-
-
Save tompee26/d3e7b876ec426c0ad83ed248fc16d629 to your computer and use it in GitHub Desktop.
Event aggregator
This file contains hidden or 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 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