Skip to content
jonathanpeppers edited this page Mar 16, 2013 · 2 revisions

This is a simple messenger for sending loosely coupled messages out to multiple subscribers. I feel this is critical for the nature of cross platform apps. Sometimes ViewModels need to send events to the View and vice versa, this is an easy way to make that happen.

Examples:

//First make a Message class
class MyMessage : Message { public MyMessage(object sender) : base(sender) { } }

//Now any class can register such as
var messenger = new Messenger();
messenger.Subscribe<MyMessage>(m => {
    //Do something here
});

//Or use a method    
messenger.Subscribe<MyMessage>(MyMethod);

//For cleanliness, use in combination with ServiceContainer
var messenger = ServiceContainer.Resolve<IMessenger>();

//To send a message
messenger.Publish(new MyMessage(this));

//To unsubscribe
messenger.Unsubscribe<MyMessage>(MyMethod);

Notes:

  • Messenger uses WeakReference so if you forget to unsubscribe, there shouldn't be a memory leak
  • This is great for application level events, such as backgrounding/foregrounding the app, etc.
Clone this wiki locally