Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * 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("")
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement