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.

59 lines
1.5KB

  1. using System;
  2. namespace Svelto.Observer
  3. {
  4. public abstract class Observer<DispatchType, ActionType>: IObserver<ActionType>
  5. {
  6. public Observer(Observable<DispatchType> observable)
  7. {
  8. observable.Notify += OnObservableDispatched;
  9. _unsubscribe = () => observable.Notify -= OnObservableDispatched;
  10. }
  11. public void AddAction(Action<ActionType> action)
  12. {
  13. _actions += action;
  14. }
  15. public void RemoveAction(Action<ActionType> action)
  16. {
  17. _actions += action;
  18. }
  19. public void Unsubscribe()
  20. {
  21. _unsubscribe();
  22. }
  23. private void OnObservableDispatched(DispatchType dispatchNotification)
  24. {
  25. _actions(TypeMap(dispatchNotification));
  26. }
  27. abstract protected ActionType TypeMap(DispatchType dispatchNotification);
  28. Action<ActionType> _actions;
  29. Action _unsubscribe;
  30. }
  31. public class Observer<DispatchType>: Observer<DispatchType, DispatchType>
  32. {
  33. public Observer(Observable<DispatchType> observable):base(observable)
  34. {}
  35. protected override DispatchType TypeMap(DispatchType dispatchNotification)
  36. {
  37. return dispatchNotification;
  38. }
  39. }
  40. public interface IObserver<WatchingType>
  41. {
  42. void AddAction(Action<WatchingType> action);
  43. void RemoveAction(Action<WatchingType> action);
  44. void Unsubscribe();
  45. }
  46. }