private IDisposable SubscribeInternal(string id, UnityMessageDelegate handler) { lock (this.stateLock) { Subscription subscriptionInfo = null; Subscription[] list; if (this.subscriptions.TryGetValue(id, out list)) { subscriptionInfo = list.FirstOrDefault(m => m.handler == handler); if (subscriptionInfo == null) { Array.Resize(ref list, list.Length + 1); this.subscriptions[id] = list; } } else { list = new Subscription[1]; this.subscriptions.Add(id, list); } if (subscriptionInfo == null) { subscriptionInfo = new Subscription( id, handler, (self) => this.Unsubscribe(self)); list[list.Length - 1] = subscriptionInfo; } return(subscriptionInfo); } }
/// <summary> /// Subscribes a new message handler to listen for a given message id. /// </summary> /// <param name="id">The message id.</param> /// <param name="handler">The message handler.</param> /// <returns>Disposable instance that unsubscribes handler when disposed.</returns> public static IDisposable Subscribe(string id, UnityMessageDelegate handler) => UnityMessageManager.instance?.SubscribeInternal(id, handler);
public Subscription(string id, UnityMessageDelegate handler, Action <Subscription> unsubscription) { this.id = id; this.handler = handler; this.unsubscription = unsubscription; }