Mirror of Svelto.ECS because we're a fan of it
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Observer.cs 2.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. using System;
  2. namespace Svelto.Observer.InterNamespace
  3. {
  4. public abstract class Observer<DispatchType, ActionType> : IObserver<ActionType>
  5. {
  6. protected Observer(Observable<DispatchType> observable)
  7. {
  8. observable.Notify += OnObservableDispatched;
  9. _unsubscribe = () => observable.Notify -= OnObservableDispatched;
  10. }
  11. public void AddAction(ObserverAction<ActionType> action)
  12. {
  13. _actions += action;
  14. }
  15. public void RemoveAction(ObserverAction<ActionType> action)
  16. {
  17. _actions -= action;
  18. }
  19. public void Unsubscribe()
  20. {
  21. _unsubscribe();
  22. }
  23. void OnObservableDispatched(ref DispatchType dispatchNotification)
  24. {
  25. if (_actions != null)
  26. {
  27. var actionType = TypeMap(ref dispatchNotification);
  28. _actions(ref actionType);
  29. }
  30. }
  31. protected abstract ActionType TypeMap(ref DispatchType dispatchNotification);
  32. ObserverAction<ActionType> _actions;
  33. Action _unsubscribe;
  34. }
  35. }
  36. namespace Svelto.Observer.IntraNamespace
  37. {
  38. public class Observer<DispatchType> : InterNamespace.Observer<DispatchType, DispatchType>
  39. {
  40. public Observer(Observable<DispatchType> observable) : base(observable)
  41. { }
  42. protected override DispatchType TypeMap(ref DispatchType dispatchNotification)
  43. {
  44. return dispatchNotification;
  45. }
  46. }
  47. }
  48. namespace Svelto.Observer
  49. {
  50. public class Observer: IObserver
  51. {
  52. public Observer(Observable observable)
  53. {
  54. observable.Notify += OnObservableDispatched;
  55. _unsubscribe = () => observable.Notify -= OnObservableDispatched;
  56. }
  57. public void AddAction(Action action)
  58. {
  59. _actions += action;
  60. }
  61. public void RemoveAction(Action action)
  62. {
  63. _actions -= action;
  64. }
  65. public void Unsubscribe()
  66. {
  67. _unsubscribe();
  68. }
  69. void OnObservableDispatched()
  70. {
  71. if (_actions != null)
  72. _actions();
  73. }
  74. Action _actions;
  75. readonly Action _unsubscribe;
  76. }
  77. public interface IObserver<WatchingType>
  78. {
  79. void AddAction(ObserverAction<WatchingType> action);
  80. void RemoveAction(ObserverAction<WatchingType> action);
  81. void Unsubscribe();
  82. }
  83. public interface IObserver
  84. {
  85. void AddAction(Action action);
  86. void RemoveAction(Action action);
  87. void Unsubscribe();
  88. }
  89. }