TinyMessenger is an event aggregator that allows for loosely coupled communication between classes. It provides a central hub for publishing and subscribing to messages. Classes can publish messages to the hub asynchronously, and subscribe to receive specific messages by message type or predicate. Subscriptions return a token that can be used to unsubscribe. Messages are simple classes that implement an interface. Proxies can also be used to deliver messages in a specific context like a UI thread.
2. Some scenarios
Communication between Controllers/ViewModels.
Service classes raising "events".
Removing responsibilities from classes that receive external
events (such as the AppDelegate in an iPhone application).
Decoupling communication between classes.
3. How to use?
var hub= new TinyMessengerHub();
Or
var hub = container.Resolve<ITinyMessengerHub>();
4. How? Publishing
//Publishing a message
hub.Publish(new MyMessage());
//asyncronously if necessary
hub.PublishAsync(new MyMessage());
// callback when publishing is completed
hub.PublishAsync(new MyMessage(), MyCallback);
// MyCallback is executed on completion
5. How ? Subscribing
//Subscribe regardless of how many publishers there are
hub.Subscribe<MyMessage>((m) => { MessageBox.Show("Message Received!"); });
// only receive the message if the content container "Testing"
hub.Subscribe<MyMessageAgain>((m) => { MessageBox.Show("Message
Received!"); }, (m) => m.Content == "Testing");
//Via proxy
hub.Subscribe<MyMessage>((m) => { MessageBox.Show("Received via proxy"); },
DefaultTinyMessageProxy.Instance);
//
hub.Subscribe<MyMessageAgain>((m) => { MessageBox.Show("Message
Received!"); }, (m) => m.Content == "Testing", true,
DefaultTinyMessageProxy.Instance);
6. How ? Unsubscribing
var token = hub.Subscribe<MyMessage>((m) => { MessageBox.Show("Message
Received!"); });
//Unscubscribing
messenger.Unsubscribe<TestMessage>(token );
//other way:
token.Dispose()
7. Messages, How to define?
//Simplest
public class MyMessage : ITinyMessage
{
public object Sender { get; private set; }
}
//General
public class MyMessageAgain : GenericTinyMessage<String>
{
public MyMessageAgain(object sender, String content)
: base(sender, content)
{
// We now have a public string property called Content
}
}
//If any subscribers call "Cancel" on our
bool isCancelled = false;
hub.Publish(new CancellableGenericTinyMessage<string>(this, "Testing", () => { isCancelled = true; }));
8. Proxy, How to define?
// This example proxy (for WPF/Silverlight) uses the despatcher to // marshall messages
back to the UI thread:
public class DispatcherTinyMessageProxy : ITinyMessageProxy
{
private Dispatcher _Dispatcher;
public DispatcherTinyMessageProxy(Dispatcher dispatcher)
{
_Dispatcher = dispatcher;
}
public void Deliver(ITinyMessage message, ITinyMessageSubscription
subscription)
{
_Dispatcher.Invoke((Action)delegate { subscription.Deliver(message); });
}
}