actor_event.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. package mhayaActor
  2. import (
  3. cfacade "github.com/mhaya/facade"
  4. clog "github.com/mhaya/logger"
  5. )
  6. type actorEvent struct {
  7. thisActor *Actor // parent
  8. queue // queue
  9. funcMap map[string][]IEventFunc // register event func map
  10. }
  11. func newEvent(thisActor *Actor) actorEvent {
  12. return actorEvent{
  13. thisActor: thisActor,
  14. queue: newQueue(),
  15. funcMap: make(map[string][]IEventFunc),
  16. }
  17. }
  18. // Register 注册事件
  19. // name 事件名
  20. // fn 接收事件处理的函数
  21. func (p *actorEvent) Register(name string, fn IEventFunc) {
  22. funcList := p.funcMap[name]
  23. funcList = append(funcList, fn)
  24. p.funcMap[name] = funcList
  25. }
  26. func (p *actorEvent) Registers(names []string, fn IEventFunc) {
  27. for _, name := range names {
  28. p.Register(name, fn)
  29. }
  30. }
  31. // Unregister 注销事件
  32. // name 事件名
  33. func (p *actorEvent) Unregister(name string) {
  34. delete(p.funcMap, name)
  35. }
  36. func (p *actorEvent) Push(data cfacade.IEventData) {
  37. if _, found := p.funcMap[data.Name()]; found {
  38. p.queue.Push(data)
  39. }
  40. if p.thisActor.Path().IsChild() {
  41. return
  42. }
  43. p.thisActor.Child().Each(func(iActor cfacade.IActor) {
  44. if childActor, ok := iActor.(*Actor); ok {
  45. childActor.event.Push(data)
  46. }
  47. })
  48. }
  49. func (p *actorEvent) Pop() cfacade.IEventData {
  50. v := p.queue.Pop()
  51. if v == nil {
  52. return nil
  53. }
  54. eventData, ok := v.(cfacade.IEventData)
  55. if !ok {
  56. clog.Warnf("Convert to IEventData fail. v = %+v", v)
  57. return nil
  58. }
  59. return eventData
  60. }
  61. func (p *actorEvent) funcInvoke(data cfacade.IEventData) {
  62. funcList, found := p.funcMap[data.Name()]
  63. if !found {
  64. clog.Warnf("[%s] Event not found. [data = %+v]",
  65. p.thisActor.Path(),
  66. data,
  67. )
  68. return
  69. }
  70. defer func() {
  71. if rev := recover(); rev != nil {
  72. clog.Errorf("[%s] Event invoke error. [data = %+v]",
  73. p.thisActor.Path(),
  74. data,
  75. )
  76. }
  77. }()
  78. for _, eventFunc := range funcList {
  79. eventFunc(data)
  80. }
  81. }
  82. func (p *actorEvent) onStop() {
  83. p.funcMap = nil
  84. p.queue.Destroy()
  85. p.thisActor = nil
  86. }