UrhoEventAdapter.cs 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. using System;
  2. using System.Collections.Generic;
  3. namespace Urho
  4. {
  5. internal class UrhoEventAdapter<TEventArgs>
  6. {
  7. readonly Dictionary<IntPtr, List<Action<TEventArgs>>> managedSubscribersByObjects;
  8. readonly Dictionary<IntPtr, Subscription> nativeSubscriptionsForObjects;
  9. public UrhoEventAdapter()
  10. {
  11. managedSubscribersByObjects = new Dictionary<IntPtr, List<Action<TEventArgs>>>();
  12. nativeSubscriptionsForObjects = new Dictionary<IntPtr, Subscription>();
  13. }
  14. public void AddManagedSubscriber(IntPtr handle, Action<TEventArgs> action, Func<Action<TEventArgs>, Subscription> nativeSubscriber)
  15. {
  16. List<Action<TEventArgs>> listOfManagedSubscribers;
  17. if (!managedSubscribersByObjects.TryGetValue(handle, out listOfManagedSubscribers))
  18. {
  19. listOfManagedSubscribers = new List<Action<TEventArgs>> { action };
  20. managedSubscribersByObjects[handle] = listOfManagedSubscribers;
  21. nativeSubscriptionsForObjects[handle] = nativeSubscriber(args =>
  22. {
  23. foreach (var managedSubscriber in listOfManagedSubscribers)
  24. {
  25. managedSubscriber(args);
  26. }
  27. });
  28. }
  29. else
  30. {
  31. //this handle is already subscribed to the native event - don't call native subscription again - just add it to the list.
  32. listOfManagedSubscribers.Add(action);
  33. }
  34. }
  35. public void RemoveManagedSubscriber(IntPtr handle, Action<TEventArgs> action)
  36. {
  37. List<Action<TEventArgs>> listOfManagedSubscribers;
  38. if (managedSubscribersByObjects.TryGetValue(handle, out listOfManagedSubscribers))
  39. {
  40. listOfManagedSubscribers.RemoveAll(a => a == action);
  41. if (listOfManagedSubscribers.Count < 1)
  42. {
  43. managedSubscribersByObjects.Remove(handle);
  44. nativeSubscriptionsForObjects[handle].Unsubscribe();
  45. }
  46. }
  47. }
  48. }
  49. }