public Subscription(Action <TEventBase> action, SubscriptionToken token) { if (action == null) { throw new ArgumentNullException("action"); } if (token == null) { throw new ArgumentNullException("token"); } _action = action; SubscriptionToken = token; }
/// <summary> /// Subscribes to the specified event type with the specified action /// </summary> /// <typeparam name="TEventBase">The type of event</typeparam> /// <param name="action">The Action to invoke when an event of this type is published</param> /// <returns>A <see cref="SubscriptionToken"/> to be used when calling <see cref="Unsubscribe"/></returns> public SubscriptionToken Subscribe <TEventBase>(Action <TEventBase> action) where TEventBase : EventBase { if (action == null) { throw new ArgumentNullException(nameof(action)); } lock (SubscriptionsLock) { if (!_subscriptions.ContainsKey(typeof(TEventBase))) { _subscriptions.Add(typeof(TEventBase), new List <ISubscription>()); } var token = new SubscriptionToken(typeof(TEventBase)); _subscriptions[typeof(TEventBase)].Add(new Subscription <TEventBase>(action, token)); return(token); } }
/// <summary> /// Unsubscribe from the Event type related to the specified <see cref="SubscriptionToken"/> /// </summary> /// <param name="token">The <see cref="SubscriptionToken"/> received from calling the Subscribe method</param> public void Unsubscribe(SubscriptionToken token) { if (token == null) { throw new ArgumentNullException(nameof(token)); } lock (SubscriptionsLock) { if (_subscriptions.ContainsKey(token.EventItemType)) { var allSubscriptions = _subscriptions[token.EventItemType]; var subscriptionToRemove = allSubscriptions.FirstOrDefault(x => x.SubscriptionToken.Token == token.Token); if (subscriptionToRemove != null) { _subscriptions[token.EventItemType].Remove(subscriptionToRemove); } } } }
public Subscription(Action <TEventBase> action, SubscriptionToken token) { _action = action ?? throw new ArgumentNullException(nameof(action)); SubscriptionToken = token ?? throw new ArgumentNullException(nameof(token)); }