For the last part of this Getting started Xamarin with Prism series, I would like to discuss about using Messaging in Xamarin forms. We will use our previous project from our Part3 of the getting started series and here is the link for the Repository: https://github.com/KirkPatrickJunsay/XamarinPrismSample
What is Messaging ?
Messaging is just based on the Publisher – Subscriber design pattern where in your application contains two major players. First the Publisher, contains a series of codes that will execute once a specific event happened. Then lastly your Subscriber is the one receiving something in return due to that event which is called a Message. Xamarin Forms has it’s own Messaging called Messaging Center but the problem is it’s static and as per Brian Lagunas it’s not testable. So what he came up in prism is the so called IEventAggregator.
Features of IEventAggregator:
- Loosely coupled and event based communication
- There are multiple Publishers and Subscribers
- It can pass Parameters or Payloads
- It Can filter Events
- They are weak events meaning you have no worries in unsubscribing from events.
So let’s modify our current Xamarin Prism Sample project Application by adding first a new folder called Events.
Then let’s create a new class called SampleEvent under the Events folder.
Then let’s try to inherit from the PubSubEvent class with a string type payload shown in Figure 3. then let’s leave it as is.
Next thing is to do is to have a publisher. Our scenario here by the way is that when we click the Back button from Page 2 will fire an event right away and our subscriber will be our Page 1. The Page2 will contain the payload that the Page1 will display in it’s newly added Greeting property. Now for the Page 2 publisher setup we need first to get the instance of IEventAggregator from our ViewModel constructor which makes it more loosely coupled as shown in Figure 4.
Let’s wire up our event in our NavigatePreviousPage method by getting our event Class SampleEvent then publish a string payload like in Figure 5.
Then for the last step we need to setup our subscriber in our Page1ViewModel. Let’s get the instance of our IEventAggregator from it’s constructor then subscribe from the SampleEvent class with a method Called UpdateGreeting that’s just setting our Greeting property as shown in Figure 6.
Let’s try to run our application and see the power of Messaging in Prism. As you can see in the demo the payload (“Something Happened”) of the publisher from Page 2 was displayed in our Page 1.
Just a quick wrap for the things we have learned in Messaging. First Prism’s implementation of Messaging is good because it’s loosely coupled and second we have a full testable implementation because it is not static implementation compared to the Messaging Center of Xamarin Forms. Lastly you don’t need to worry about unsubscribing with events because prism is handling it for you.
Happy Coding 🙂