Advertisement
Guest User

Untitled

a guest
Oct 18th, 2019
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.70 KB | None | 0 0
  1. /**
  2. * This is a generic event class. It simply allows subscription and invocation.
  3. */
  4. class Event<T> {
  5. private val handlers = arrayListOf<(Event<T>.(T) -> Unit)>()
  6. operator fun plusAssign(handler: Event<T>.(T) -> Unit) { handlers.add(handler) }
  7. operator fun invoke(value: T) { for (handler in handlers) handler(value) }
  8. }
  9.  
  10. /**
  11. * Each controller would have a companion object which would be the event emitted by
  12. * each endpoint. The event would be a tuple of the function invoked and its payload.
  13. */
  14. class SomeController {
  15. companion object {
  16. var eventEmitted = Event<Pair<String, String>>()
  17. }
  18.  
  19. fun post(body: Any): String {
  20. // Ideally this "eventEmitted" invocation could be abstracted away in a parent class?
  21. eventEmitted(Pair("SomeController::post", "post method invoked"))
  22. return "Return POST value"
  23. }
  24.  
  25. fun get(): String {
  26. eventEmitted(Pair("SomeController::get", "get method invoked"))
  27. return "Return GET value"
  28. }
  29. }
  30.  
  31. /**
  32. * The Notifications is the one which handles which events trigger which logic. Potentially there could
  33. * be some sugar syntax applied here to not have to do the whole if/then ceremony.
  34. */
  35. class NotificationsManager {
  36. fun setupEvents() {
  37. SomeController.eventEmitted += { if (it.first == "SomeController::get") println("get's event payload >>> ${it.second}") }
  38. SomeController.eventEmitted += { if (it.first == "SomeController::post") println("post's event payload >>> ${it.second}") }
  39. }
  40. }
  41.  
  42. /**
  43. * Runnable example :)
  44. */
  45. fun main(args : Array<String>) {
  46. val controller = SomeController()
  47. NotificationsManager().setupEvents()
  48. controller.get()
  49. controller.get()
  50. controller.post("")
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement