-
-
Save manzanit0/c78cb6e3c26193dc48ec8fd8b9c386c6 to your computer and use it in GitHub Desktop.
An use case for synthetic events in Kotlin
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
/** | |
* This is a generic event class. It simply allows subscription and invocation. | |
*/ | |
class Event<T> { | |
private val handlers = arrayListOf<(Event<T>.(T) -> Unit)>() | |
operator fun plusAssign(handler: Event<T>.(T) -> Unit) { handlers.add(handler) } | |
operator fun invoke(value: T) { for (handler in handlers) handler(value) } | |
} | |
/** | |
* Each controller would have a companion object which would be the event emitted by | |
* each endpoint. The event would be a tuple of the function invoked and its payload. | |
*/ | |
class SomeController { | |
companion object { | |
var eventEmitted = Event<Pair<String, String>>() | |
} | |
fun post(body: Any): String { | |
// Ideally this "eventEmitted" invocation could be abstracted away in a parent class? | |
eventEmitted(Pair("SomeController::post", "post method invoked")) | |
return "Return POST value" | |
} | |
fun get(): String { | |
eventEmitted(Pair("SomeController::get", "get method invoked")) | |
return "Return GET value" | |
} | |
} | |
/** | |
* The Notifications is the one which handles which events trigger which logic. Potentially there could | |
* be some sugar syntax applied here to not have to do the whole if/then ceremony. | |
*/ | |
class NotificationsManager { | |
fun setupEvents() { | |
SomeController.eventEmitted += { if (it.first == "SomeController::get") println("get's event payload >>> ${it.second}") } | |
SomeController.eventEmitted += { if (it.first == "SomeController::post") println("post's event payload >>> ${it.second}") } | |
} | |
} | |
/** | |
* Runnable example :) | |
*/ | |
fun main(args : Array<String>) { | |
val controller = SomeController() | |
NotificationsManager().setupEvents() | |
controller.get() | |
controller.get() | |
controller.post("") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment