Created
January 17, 2015 20:44
-
-
Save scionwest/e548179e5c09c0f547b8 to your computer and use it in GitHub Desktop.
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
| internal class ChatMessageHandler<TMessage> : INotificationHandler<TMessage> where TMessage : ChatMessage | |
| { | |
| /// <summary> | |
| /// The callbacks invoked when the handler processes the messages. | |
| /// </summary> | |
| private Action<TMessage, ISubscription> callback; | |
| /// <summary> | |
| /// The conditions that must be met in order to fire the callbacks. | |
| /// </summary> | |
| private Func<TMessage, bool> condition; | |
| /// <summary> | |
| /// Registers a callback for when a chat message is published by the MessageCenter | |
| /// </summary> | |
| /// <param name="processor">The message.</param> | |
| /// <returns></returns> | |
| public void Register( | |
| Action<TMessage, ISubscription> processor, | |
| Func<TMessage, bool> condition) | |
| { | |
| this.callback = processor; | |
| this.condition = condition; | |
| } | |
| /// <summary> | |
| /// Unsubscribes the handler from notifications. This cleans up all of the callback references and conditions. | |
| /// </summary> | |
| public void Unsubscribe(INotificationCenter notificationCenter) | |
| { | |
| this.callback = null; | |
| this.condition = null; | |
| // Let the notification manager know we are unsubscribing. | |
| notificationCenter.Unsubscribe<TMessage>(this); | |
| } | |
| /// <summary> | |
| /// Processes the message by verifying the callbacks can be invoked, then invoking them. | |
| /// </summary> | |
| /// <param name="message">The message.</param> | |
| public void ProcessMessage(TMessage message) | |
| { | |
| if (!CanProcess(message)) | |
| { | |
| return; | |
| } | |
| Post(message); | |
| } | |
| /// <summary> | |
| /// Determines whether this instance can post notifications with the specified message. | |
| /// </summary> | |
| /// <param name="message">The message.</param> | |
| /// <returns></returns> | |
| private bool CanProcess(TMessage message) | |
| { | |
| // If any of the conditions fail, don't process. | |
| return this.condition(message); | |
| } | |
| /// <summary> | |
| /// Posts the specified message as a notification to the callback. | |
| /// </summary> | |
| /// <param name="message">The message.</param> | |
| private void Post(TMessage message) | |
| { | |
| this.callback(message, this); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment