An Introduction to Xamarin.Forms and Messaging

Ever since Xamarin 3 was introduced, there's been quite a bit of buzz around it. The idea of being able to create a mobile application, including the user interface, using a single code base is amazing. But Xamarin.Forms is so much more than that. One of the often overlooked features included in Xamarin.Forms is the concept of Messaging and that is the topic of this tutorial.

1. What is messaging?

If you have experience writing software in enterprise environments, you may also have experience with—or have at least heard of—messaging in your applications. Messaging is a term used to describe applications that take advantage of the publish/subscribe (pub/sub) design pattern. The publish/subscribe architecture is made up of three primary players:

  • messages
  • publishers
  • subscribers

The central focus of this process is around the messages. Messages are simply a way to transmit information about a certain event that has occurred. This event is typically tied to some sort of business process and it contains information required by systems that will ultimately use this data to perform some other operation.

The other two players, publishers and subscribers, are the purveyors of these messages. As the names imply, the publishers are the senders of the messages and the subscribers are the receivers of the messages.

How does messaging work?

The basic process of messaging is rather simple. Within a system, a certain event occurs. This event could be something simple, like a user clicking a button, or as complex as a business rule firing in a large financial firm's trading application. In the world of messaging, there is little difference between these two things. All you need to know is that something has happened.

When an event occurs, a publisher will take the information about this event and bundle it up into a message. This message will have some sort of type tied to it as well as additional data describing the event. The type is very important later in the process. Once this message is created, the publisher will send it out into some system. From that point, the publisher no longer cares about this event or message. There are some types of publishers that need to get a response, but that isn't very important in our case.

On the other end of the equation are the subscribers. Subscribers are the exact opposite of the publishers. They wait for messages of a certain type to be published. This is where their name comes from, they are subscribed to certain types of events. When a subscriber sees that an event to which they are subscribed has occurred, it will take this message and all of its data, and do something with it. Once this process is complete, the subscriber goes back to waiting for more messages.

Why should you use messaging?

With this architecture in mind, you may be wondering why or when you should use it. Typically, developers choose to use this type of architecture for two reasons, loose coupling and scalability.

Loose Coupling

In terms of software development, loose coupling is the concept of keeping different components within your application as separate as possible to the point that they know as little about each other as possible. This separation allows developers to focus more on the functionality of a system and less on the interaction of different components or pieces of the system. This allows for easier changes of functionality and testing of different components.

Scalability

Scalability has to do with how a system can grow without having to constantly rework and re-architect the entire solution. When it comes to messaging, if you need to do some sort of additional processing when a particular message is detected, a new subscriber is created to handle that functionality as opposed to having to open up an existing piece of code and make changes.

Now, let's see how we can put this extremely powerful architecture to use in our mobile applications using Xamarin.

2. Utilizing Messaging in Xamarin.Forms

Entering into the world of messaging in Xamarin.Forms is actually quite simple now that we understand the basic concepts of messaging. All we need now is a construct to access them. Luckily for us, there is only one class we really need to worry about and that is MessagingCenter. The MessagingCenter class is part of Xamarin.Forms and has methods to help us with both publishing and subscribing to messages. Let's take a look at each.

Publish

The first method we are going to take a look at in the MessagingCenter class is Send. Although the concept in a messaging context is publish, the Xamarin.Forms implementation uses Send. There are two versions of the Send method that can be used to publish data.

  • MessagingCenter.Send<TSender>(TSender sender, string message)
  • MessagingCenter.Send<TSender, TArgs>(TSender sender, string message, TArgs args)

Both of these options are generic. The first allows you to specify the sender of this message and the second also allows a secondary argument, the payload type.

It's important to point out that the TArgs generic parameter can be any type. It can be something simple like a string or as complex as a custom type.

Subscribe

Now that we understand how to publish, or Send, messages into the system, it's time for something to subscribe to them. To do that, we will be using the Subscribe method on the MessagingCenter class.

Similar to the two versions of the Send method, the Subscribe method also has two overloads.

  • MessagingCenter.Subscribe<TSender>(object subscriber, string message, Action<TSender> callback, TSender sender = null)
  • MessagingCenter.Subscribe<TSender, TArgs>(object subscriber, string message, Action<TSender, TArgs> callback, TSender sender = null)

For the Subscribe methods, we are specifying who the subscriber is. Typically we will be specifying this for the first parameter. The second parameter will contain the same message name that was specified in the Send method so we can be notified when that particular message has been sent. The third parameter is a generic delegate that accepts the sender, and possibly args, depending on which version of the method is used. The delegate is a callback that is executed when a message of this type is published. Finally is a nullable parameter specifying which TSender this message should be subscribed for. It can be left as null to accept this type of message from any sender.

Great, now we are subscribing to messages, but what if we don't care about certain messages anymore? Good question. There is one more method to take into consideration.

Unsubscribe

An often overlooked process in the world of messaging is unsubscribing. When you are working in a very large enterprise class infrastructure, maybe it isn't quite as important. In contrast, when you are working in a smaller environment, such as a phone, it becomes more important.

Even though using the messaging architecture allows more flexibility and scalability, it still takes system resources. Because of this, we can't continue to increase the number of subscribers in a system infinitely. That being the case, we need to be respectful of resources as best we can. In Xamarin.Forms, the way that we do this is through calling the Unsubscribe method. This method allows us to say that we no longer care about a particular message being published out to the system.

The Unsubscribe method also has two overloads.

  • MessagingCenter.Unsubscribe<TSender>(object subscriber, string message)
  • MessagingCenter.Unsubscribe<TSender, TArgs>(object subscriber, string message)

You may notice that the generic arguments don't manifest themselves in the parameter list. Only the developers have a good idea as to why exactly, but I feel that it is probably more of a formality. Either way, I choose to be consistent across all my calls to Send, Subscribe, and Unsubscribe, and use the same signatures and arguments to eliminate any sort of confusion.

Now that we understand the basic concepts of messaging, it's time to create a simple example utilizing these ideas.

3. Creating an Example

In this example, we will create a simple Xamarin.Forms app that will use all three methods of the MessagingCenter class mentioned previously in this article. The app itself may seem rather inconsequential, but it will provide a useful illustration of how to use these concepts in your apps going forward.

Step 1: Create a Xamarin.Forms App

We'll start by creating a new Xamarin.Forms app. To accomplish this, simply open Xamarin Studio (or Visual Studio) and select File > New Solution. In the New Solution dialog, select the Mobile Apps template family and choose one of the templates. I will select the PCL version, but you could use the Shared Project version if you like.

Step 2: Add Some Code

Once the solution is created, let's add some code. In the shared project, create a new class and name it MainPage. This will be the screen in the application that will contain the user interface as well as the logic. This can obviously be broken out into more logical pieces, but this application is simple enough that I didn't think it was necessary.

Replace the contents of the MainPage.cs file with the following:

This may initially seem a little overwhelming, but I assure you that it is quite simple. There are three buttons:

  • Publish: uses the Send method to publish a message with a name of boom
  • Subscribe/Unsubscribe: flips the page from being subscribed/unsubscribed from boom
  • Clear: clears the contents of ListView

The basic premise of this application is that it starts in an unsubscribed state. In this state, if you tap the Publish button, nothing seems to happen. We know that the boom message is being published, but since there are no subscribers, nothing happens.

Once you tap the Subscribe button, the application goes into a subscribed state in which it is now listening for the boom message. When it receives this message, it places a new DateTime value into the _eventTimes collection, which gets updated into the _eventList ListView via an ObservableCollection.

The rest of the code is just some basic formatting and spacing. 

Step 3: Build and Run

Running the application in the iOS Simulator should look similar to this:

Similarly, the initial state in the Android Emulator should look like this:

After tapping the Subscribe button and publishing a few messages, you should begin to see the user interface being updated by getting some DateTime values in the ListView.

Conclusion

There you have it. You have successfully created a Xamarin.Forms app that takes advantage of an architecture that is typically reserved for large enterprises. You should feel rather excited at this point as you now have a new tool in your tool belt that will allow you to create very scalable and flexible—not to mention testable—applications that can run in the hand of the end user. And that can open the door to many more possibilities.

Tags:

Comments

Related Articles