Advertisement
Guest User

Untitled

a guest
Mar 22nd, 2017
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.13 KB | None | 0 0
  1. import scala.collection.mutable
  2. /**
  3. Collects subscribers that are notified whenever an event occurs.
  4. Publishers simply call fire with the arguments of this event occurence.
  5. Subscribers can provide conditions to filter out which occurences they care about.
  6. Subscribers can also provide a priority to order the notifications.
  7. Subscribers can also provide a label that they can use to unsubscribe from the event.
  8. */
  9. class Event[T] {
  10.  
  11. private class Subscriber (
  12. val label:String,
  13. val invoke : T => Unit,
  14. val condition : T => Boolean,
  15. val priority : Int
  16. ) extends Ordered[Subscriber] {
  17. def fire(args:T): Unit = {
  18. if (condition(args)) invoke(args)
  19. }
  20.  
  21. override def compare(that: Subscriber): Int = {
  22. this.priority - that.priority
  23. }
  24. }
  25.  
  26. private var subscriberList = new mutable.PriorityQueue[Subscriber]()
  27.  
  28. /**
  29. * Notifies all subscribers that an event has occurred
  30. * @param args arguments for this event firing
  31. */
  32. def fire(args : T) : Unit = {
  33. for (subscriber <- subscriberList.clone.dequeueAll) subscriber.fire(args)
  34. }
  35.  
  36. /**
  37. * Calls invocation function every time this event occurs if the condition is true
  38. * @param invocation the function to call when the event fires
  39. * @param condition only call invocation if this condition is true
  40. * @param priority higher priority subscriptions will be invoked before lower
  41. * @param label a label for removing the subscription later
  42. */
  43. def subscribe(
  44. invocation : T => Unit,
  45. condition : T => Boolean = (_:T) => true,
  46. priority : Int = 0,
  47. label : String = ""
  48. ) : Unit = {
  49. subscriberList.enqueue(new Subscriber(label, invocation, condition, priority))
  50. }
  51.  
  52. /**
  53. * Removes all subscriptions whose label is equal to withLabel
  54. * @param withLabel the label to compare against
  55. */
  56. def unsubscribe(withLabel : String) : Unit = {
  57. subscriberList = subscriberList filter ((x:Subscriber) => withLabel != x.label)
  58. }
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement