Xamarin Forms Messaging center

Messaging Center

Messaging Center enables view models and other components to communicate with, without having to know anything about each other besides a simple Message contract.

Messaging center also helps in reducing the coupling of the xamarin.forms project.

Let’s see how messaging center works:

Messaging center consist of two parts

  • Subscribe – Listen for messages with a certain signature and perform some action when they are received. Mulitple subscribers can be listening for the same message.
  • Send – Publish a message for listeners to act upon. If no listeners have subscribed then the message is ignored.

The MessagingService is a static class with Subscribe and Send methods that are used throughout the solution.

Messages have a string message parameter that is used as way to address messages. The Subscribe and Send methods use generic parameters to further control how messages are delivered – two messages with the same message text but different generic type arguments will not be delivered to the same subscriber.

The API for MessagingCenter is simple:

  • Subscribe<TSender> (object subscriber, string message, Action<TSender> callback, TSender source = null)
  • Send<TSender> (TSender sender, string message)
  • Unsubscribe<TSender> (object subscriber, string message)

we will see how to use these methods in detail in the below sample.

Getting started

Create a new Xamarin.Forms (Blank App Portable or Blank Xaml App) project in Visual studio. In this demo am going to use Xaml files to demonstrate, so am creating with Blank Xaml app.

createproject
Creating new project

I will be following MVVM pattern (who are new to MVVM can click on the link to see a basic introduction) throughout the sample, so we need to create 3 folders Model, View & ViewModel in the Portable project. In my case its XamarinForms_DependencyService (ignore the poor project naming next article will be merged with this project). Our final project structure should look like the below image.

folderstructure
Project Structure

Now am gonna add a model class, let me make it simple just add 3 classes.

1.HomeModel.cs which will contain AppName and UserName.

homemodel
HomeModel.cs

2. ProfileModel.cs which will have only UserName property

profilemodel
ProfileModel.cs

3. MessageModel.cs this is wrapper class for passing messages between objects.

MessageModel.PNG

Now we will create separate Viewmodels for both models

  1. HomePageViewModel which we will use for subscribing to messages and is binded with the view.

 

homepageviewmodel
HomePage ViewModel.cs

As you can see in the Homepage ViewModel (HPVM) constructor i have added the code

MessagingCenter.Subscribe<MessageModel>(this, "UserName", (model) =>
 {
         HomeModelProp.UserName = model.Data;
 });

this denotes HPVM is subscribed for messages with the “T” type in this sample T -> MessageModel and UserName message name, whenever a message is sent with message name “UserName” and the object type as “MessageModel” HPVM will receive it and perform an action. In this sample i have just updated the UserName property of the underlying business object i.e.HomeModel.

2. ProfilePageViewModel which will be the Message sender to the HomePage ViewModel

profilevm.PNG
ProfilePageViewModel.cs

Here the Message will be published whenever the UserName property of the ProfilePageViewModel is updated.

MessagingCenter.Send(new MessageModel() 
 {  
     Data = ProfileModelProp.UserName 
 }, "UserName");

this will publish a message with type  MessageModel and message name as “UserName”.

Now am going to create 2 views for binding the ViewModel to see how the Messaging Center is working.

1. HomePage.Xaml

ConentPage binding context is set to HomePageViewModel and also i have added 2 labels one is binded with the HomeModel.AppName and the other is binded with HomeModel.UserName and 1 button to trigger navigation.

homepageview.PNG
HomePage.Xaml
nexus-5-lollipop-screenshot-6
HomePage.Xaml

So now when clicked on the UserNameButton page will be navigated to ProfilePage.

profilepagexaml.PNG

ConentPage binding context is set to ProfilePageViewModel and also i have added 1 Entry which is binded with ProfileModel.UserName and 1 button to trigger back navigation. Now whatever is typed in the Entry of ProfilePage.xaml is binded to the ProfilePageViewModel which will trigger a Message.Send() => which will update the HomePage 2nd label with the UserName typed in the ProfilePage.

nexus-5-lollipop-screenshot-7
ProfilePage

this is a simple example of how Messaging center can be used with Xamarin.Forms, it can also be used across different projects like Portable – > android -> Portable. or Ios -> Portable all you should have is Xamarin.Forms references.

Nexus 5 (Lollipop) Screenshot 9.png
After Message is sent

 

MessagingCenter.Subscribe<MessageModel>(this, "UserName", (model) =>
 {
                  HomeModelProp.UserName = model.Data;
                  MessagingCenter.Unsubscribe<MessageModel>(this,"UserName");
 });

Note: Classes should unsubscribe from messages they no longer wish to receive.

Complete source code for this project can be downloaded from here.

Summary

In this article , we have understood how to use MessagingCenter in Xamarin.Forms development to reduce decoupling between classes & ViewModels. In the next article we will talk about understanding how DependencyService  works .

 

Advertisements

2 thoughts on “Xamarin Forms Messaging center

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s