/// <summary> /// Creates the <see cref="Subscriber{TPayload}"/>. /// </summary> /// <param name="subscriptionToken">The subscription token</param> /// <param name="synchronizationContext">The synchronization context</param> /// <param name="weakAction">The action</param> public Subscriber(SubscriptionToken subscriptionToken, SynchronizationContext synchronizationContext, WeakDelegate weakAction) : base(subscriptionToken, synchronizationContext) { if (weakAction == null) { throw new ArgumentNullException(nameof(weakAction)); } this.weakAction = weakAction; var defaultFilter = new Func <TPayload, bool>(_ => true); this.weakFilter = new WeakDelegate(defaultFilter, false); }
/// <summary> /// Allows to unsubscribe with the subscription token. /// </summary> /// <param name="token">The subscription token</param> /// <returns>True if unsubscribed</returns> public bool Unsubscribe(SubscriptionToken token) { if (token == null) { throw new ArgumentNullException(nameof(token)); } lock (subscribers) { var subscriber = subscribers.FirstOrDefault(s => s.SubscriptionToken == token); if (subscriber != null) { return(subscribers.Remove(subscriber)); } } return(false); }
/// <summary> /// Checks if a subscriber is registered for the action. /// </summary> /// <param name="action">The action</param> /// <param name="keepAlive">Allows to keep the reference alive</param> /// <returns>The subscriber options</returns> public SubscriberOptions <TPayload> Subscribe(Action <TPayload> action, bool keepAlive) { if (action == null) { throw new ArgumentNullException(nameof(action)); } var subscriptionToken = new SubscriptionToken(Unsubscribe); var weakAction = new WeakDelegate(action, keepAlive); var subscriber = new Subscriber <TPayload>(subscriptionToken, synchronizationContext, weakAction); lock (subscribers) { subscribers.Add(subscriber); } var options = new SubscriberOptions <TPayload>(subscriber); return(options); }