EventModule.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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, List<EventDelegate>> dic;
  8. public EventModule()
  9. {
  10. dic = new Dictionary<int, List<EventDelegate>>();
  11. }
  12. public void AddListener(int eventId, EventDelegate handler)
  13. {
  14. Assert.IsNotNull(handler, $"EventBus.AddListener handler is null, eventId: {eventId}");
  15. if (!dic.TryGetValue(eventId, out var handlers))
  16. {
  17. handlers = new List<EventDelegate>();
  18. dic[eventId] = handlers;
  19. }
  20. Assert.IsFalse(handlers.Contains(handler), $"EventBus.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, $"EventBus.RemoveListener handler is null, eventId: {eventId}");
  26. if (dic.TryGetValue(eventId, out var handlers))
  27. {
  28. Assert.IsTrue(handlers.Contains(handler), $"EventBus.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. foreach (var handler in handlers)
  43. {
  44. try
  45. {
  46. handler?.Invoke(eventId, args);
  47. }
  48. catch (System.Exception e)
  49. {
  50. Log.Exception($"EventBus.Notify({eventId}) Error: \n" +
  51. $"Occur: {handler.Method?.DeclaringType?.FullName + "::" + handler.Method?.Name},\n", e);
  52. }
  53. }
  54. }
  55. }
  56. public void Dispose()
  57. {
  58. dic.Clear();
  59. }
  60. }
  61. }