Created
July 31, 2018 08:58
-
-
Save simonwittber/0249eed59591e4cbdad894e3a86647c3 to your computer and use it in GitHub Desktop.
Another pub-sub system for loose coupling.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| // Example Usage: | |
| public class SomeEv : Event<SomeEv> { } | |
| public class SomeOtherEv : Event<SomeOtherEv> { } | |
| public class EVTest : MonoBehaviour | |
| { | |
| void Start() | |
| { | |
| //use pooling | |
| SomeOtherEv.Subscribe(OnEv); | |
| var e = SomeEv.New(); | |
| e.Publish(); | |
| SomeEv.Dispose(e); | |
| //or not... | |
| SomeOtherEv.New().Publish().Dispose(); | |
| } | |
| void OnEv(SomeOtherEv obj) | |
| { | |
| Debug.Log(obj); | |
| } | |
| } | |
| */ | |
| public class Event<T> : System.IDisposable where T : Event<T>, new() | |
| { | |
| static Stack<T> pool = new Stack<T>(); | |
| static List<System.Action<T>> subscribers = new List<System.Action<T>>(); | |
| public static T New() | |
| { | |
| T ev; | |
| if (pool.Count > 0) | |
| ev = pool.Pop(); | |
| else | |
| ev = new T(); | |
| return ev; | |
| } | |
| public static void Dispose(T ev) => pool.Push(ev); | |
| public T Publish() | |
| { | |
| var ev = (T)this; | |
| for (int i = 0, count = subscribers.Count; i < count; i++) | |
| subscribers[i](ev); | |
| return ev; | |
| } | |
| public static void Subscribe(System.Action<T> evListener) => subscribers.Add(evListener); | |
| public static void Unsubscribe(System.Action<T> evListener) | |
| { | |
| var idx = subscribers.IndexOf(evListener); | |
| subscribers[idx] = subscribers[subscribers.Count - 1]; | |
| subscribers.RemoveAt(subscribers.Count - 1); | |
| } | |
| public static void Clear() => subscribers.Clear(); | |
| public void Dispose() => Dispose((T)this); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment