EventModule.cs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. using System.Collections.Generic;
  2. namespace XGame.Framework
  3. {
  4. public delegate void EventDelegate(int eventId, object args);
  5. public sealed partial class EventModule : IEventModule, System.IDisposable
  6. {
  7. Dictionary<int, HashSet<EventDelegate>> dic;
  8. public EventModule()
  9. {
  10. dic = new Dictionary<int, HashSet<EventDelegate>>();
  11. }
  12. public void AddListener(int eventId, EventDelegate handler)
  13. {
  14. Assert.IsNotNull(handler, $"EventModule.AddListener handler is null, eventId: {eventId}");
  15. if (!dic.TryGetValue(eventId, out var handlers))
  16. {
  17. handlers = new HashSet<EventDelegate>();
  18. dic[eventId] = handlers;
  19. }
  20. Assert.IsFalse(handlers.Contains(handler), $"EventModule.AddListener Handler Allready Exists!! {handler.Method.DeclaringType.FullName}::{handler.Method.Name}");
  21. handlers.Add(handler);
  22. }
  23. public void RemoveListener(int eventId, EventDelegate handler)
  24. {
  25. Assert.IsNotNull(handler, $"EventModule.RemoveListener handler is null, eventId: {eventId}");
  26. if (dic.TryGetValue(eventId, out var handlers))
  27. {
  28. Assert.IsTrue(handlers.Contains(handler), $"EventModule.RemoveListener Handler Doesn't Exists!! {handler.Method.DeclaringType.FullName}::{handler.Method.Name}");
  29. handlers.Remove(handler);
  30. if (handlers.Count <= 0)
  31. dic.Remove(eventId);
  32. }
  33. }
  34. public void Notify(int eventId)
  35. {
  36. Notify(eventId, null);
  37. }
  38. public void Notify(int eventId, object args)
  39. {
  40. if (dic.TryGetValue(eventId, out var handlers))
  41. {
  42. var list = ListPool.Acquire<EventDelegate>();
  43. list.AddRange(handlers);
  44. foreach (var handler in list)
  45. {
  46. try
  47. {
  48. #if UNITY_EDITOR
  49. if (handlers.Contains(handler))
  50. #endif
  51. {
  52. handler?.Invoke(eventId, args);
  53. }
  54. }
  55. catch (System.Exception e)
  56. {
  57. Log.Exception($"EventModule.Notify({eventId}) Error: \n" +
  58. $"Occur: {handler.Method?.DeclaringType?.FullName + "::" + handler.Method?.Name},\n", e);
  59. }
  60. }
  61. ListPool.Recycle(list);
  62. }
  63. }
  64. public void Dispose()
  65. {
  66. dic.Clear();
  67. }
  68. }
  69. }