Xamarin Forms provides a mechanism to allow loosely coupled event management across the entire app called MessagingCenter. It is based on a common architecture in enterprise level applications simply called the messaging design pattern. In order to keep Models and ViewModels separated they should never reference each other but we occasionally need to send information from one to another.
Why Can’t We Reference Other ViewModels or Models?
It is common in applications to start with the best of intentions to keep code clean and simple. After a few weeks or a few months you suddenly wake up and everything is tangled together. Its a mess of dependencies and then in your next project you start with the best intentions once again and it keeps happening.
The reason maybe our fear of not duplicating code or having generic objects being passed around or not being in control of what happens from one object to another. For example if you need another ViewModel to refresh its list after an item has been added on another ViewModel you might want to call the other ViewModel to update it. But its not your responsibility to do that, raise an event that something changed and let the other ViewModel’s take care of themselves. Think of each ViewModel as its own entity, responsible only for itself.
We can do this by raising a global event and then the other Model or ViewModel is responsible for subscribing and receiving the message.
MVVMLight offers a wrapper around this but you can feel free to use that or not.
When you subscribe to an event you will want to pass in a Token to filter out the appropriate messages. As you will see in DefaultMessenger.cs you only need to pass through:
- The recipient (usually you can just send through “this”)
- A Token or specific identifier for the types of messages you want to receive
- An Action, the code to execute when the message is received.
I avoid magic strings at all costs, hence you will notice the parameter is a Token enum. This is just self defined in Token.cs and you can add what you want in there. It makes all types of events possible to raise, defined in a single location.
Sending a message is incredibly easy. Just call the send function to the token and everything is done for you. You define the type that you send the data in. It is normally good practice to define custom types for sending complex data, for example AuthenticationArgs.
You can read more detail about the Xamarin MessagingCenter here.
Misuses of MessagingCenter
While this is a legitimate pattern, it can be misused and often is. I rarely, if never, use this service in any app I build. For reasons why, have a read of Misuses of MessagingCenter.