Click here to Skip to main content
15,860,943 members
Articles / Mobile Apps / Xamarin

Getting Started with Codon - Part 3

Rate me:
Please Sign up or sign in to vote.
4.56/5 (4 votes)
4 Apr 2017CPOL3 min read 8.9K   1  
Using Codon's Messenger to pass messages between app components

Codon is a zero-dependency cross-platform MVVM framework for creating UWP, WPF, and Xamarin based applications. It provides much of what you need to rapidly create sophisticated yet maintainable applications.

Introduction

In the previous article we looked at using Codon’s settings service to store and retrieve settings. In this article, you look at enabling communication between components in your app.

The code presented herein is located in Sample001 in the Samples repository

Communication between components is an essential aspect of any mildly complex app. By using a weak referencing pub/sub messaging system you can decouple components and reduce the likelihood of memory leaks caused by event subscriptions. Codon’s pub/sub messaging service is an implementation of the IMessenger interface. It allows components in your app to subscribe to message objects of a particular type, and for other components to dispatch those messages. It’s used extensively inside Codon itself for such things as notifying subscribers that a setting has changed.

Understanding the Messenger

Codon’s IMessenger implementation uses an interface based subscription model. You nominate what messages you’d like your class to receive by implementing the IMessageSubscriber<T> interface. The CLR Type of T determines the signature or identity of the message.

This declarative approach to message subscription increases transparency because message subscription is visible at the type level.

To receive messages as they are published, a subscriber needs to call the messenger’s Subscribe method.

NOTE: If you derive fromViewModelBase the messenger’s Subscribe method is called for you in the base class constructor.

The Sample’s Page1ViewModel class declares a subscription to the ExampleMessage message by implementing the IMessageSubscriber<examplemessage> interface. See Listing 1.

Message objects can be POCOs. The `ExampleMessage` class does not derive from a Codon base class.

Behind the scenes, when the ViewModelBase class calls the messenger’s Subscribe method, the messenger creates a weak reference to the view-model and calls the ReceiveMessageAsync(ExampleMessage message) method whenever an ExampleMessage object is published.

NOTE: You can unsubscribe from the IMessenger by calling its Unsubscribe method.

Listing 1. Page1ViewModel Implements the IMessageSubscriber<examplemessage> interface.

C#
public class Page1ViewModel : ViewModelBase, 
		IMessageSubscriber<examplemessage>
    {
...
	public Task ReceiveMessageAsync(ExampleMessage message)
	{
		dialogService.ShowMessageAsync(
			"Received the message.", "Message from App");

		return Task.FromResult<object>(null);
	}
...
}

If an object calls the messenger’s PublishAsync method using an ExampleMessage object as the parameter, the page receives the message.

Dispatching a Message from the View-Model

The Page1ViewModel class contains a PublishMessageCommand, which is bound to a button in the view.

C#
ActionCommand publishMessageCommand;

public ICommand PublishMessageCommand => publishMessageCommand 
          ?? (publishMessageCommand = new ActionCommand(PublishMessage));

When the button is tap/clicked, the PublishMessage method is called. See Listing 2.

The ViewModelBase class contains a Messenger, which means we don’t need to use the dependency injection to retrieve it.

NOTE: PublishAsync is an awaitable method, which is useful, for example, if your message object contains a property allowing an action to be cancelled. Codon has some prebaked messages to use for this purpose. An example of which is the CancellableMessageBase class.

Listing 2: Page1ViewModel PublishMessage method.

C#
void PublishMessage(object arg)
{
	Messenger.PublishAsync(new ExampleMessage(), true);
}

Tapping the Publish Message button on Page 1 dispatches the message, and it is received within the same view-model. See Figure 1.

Although pointless, it demonstrates how to send and receive a message. You wouldn’t ordinarily subscribe to a message that is only dispatched from the same class.

 

Dialog confirming message received

Figure 1. Dialog box confirms message received.

 

Pro Tip: Some classes in Codon, such as the Messenger and ActionCommand classes implement a global exception handling system. By default, if an exception is raised by one of these classes, the default exception handler class, LoggingExceptionHandler, logs the exception and request that the exception be rethrown. This alleviates the need to wrap all code blocks in try/catch blocks.

NOTE: While UWP and WPF have the means to catch unhandled exceptions, the same is not true for Android. If there’s an unhandled exception in your Android app, the OS will terminate it. It is recommended that you implement your own IExceptionHandler and register it with the IoC container, like so:

C#
Dependency.Register<IExceptionHandler>(() => new MyExceptionHandler(), true);

Conclusion

In this article, you looked at enabling communication between components using the Messenger class. In the next part, you look at navigating between pages using the navigation service.

I hope you find this project useful. If so, then please rate it and/or leave feedback below.

History

April 2 2017

  • First published

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Engineer
Switzerland Switzerland
Daniel is a former senior engineer in Technology and Research at the Office of the CTO at Microsoft, working on next generation systems.

Previously Daniel was a nine-time Microsoft MVP and co-founder of Outcoder, a Swiss software and consulting company.

Daniel is the author of Windows Phone 8 Unleashed and Windows Phone 7.5 Unleashed, both published by SAMS.

Daniel is the developer behind several acclaimed mobile apps including Surfy Browser for Android and Windows Phone. Daniel is the creator of a number of popular open-source projects, most notably Codon.

Would you like Daniel to bring value to your organisation? Please contact

Blog | Twitter


Xamarin Experts
Windows 10 Experts

Comments and Discussions

 
-- There are no messages in this forum --