Chapter 5. Message Passing

Message passing is a very broad and sometimes contentious topic in computer science, and there are many patterns and systems that have come and gone or abided, like “pub/sub” (“publish” and “subscribe”), event dispatchers, callbacks, observers, message queues, etc. The truth is, these are often very similar, and you’d be hard pressed to define practical differences between some of them. Regardless, this is a critical function in any application, and there are some consensus strategies in mobile application development that we’ll explain here.

Tasks

In this chapter, you’ll learn to:

  1. Use a callback to react to an operation.

  2. Dispatch a message to any interested subscribers.

  3. Listen for and react to messages dispatched within a system.

Android

In Android, you usually use callbacks for direct message passing and dispatch events with the statistically available and thread-safe LocalBroadcastManager. Note that LocalBroadcastManager sends Intent instances to be received by BroadcastReceiver instances—this is the same mechanism used by system-wide messages, many provided by other apps or operating system components; however, LocalBroadcastManager only notifies BroadcastReceivers in your app, which is both a good thing (safe) but also a little limiting—if you want to communicate between apps or with the underlying framework, you have to go beyond the brevity and simple API provided by LocalBroadcastManager.

Use a Callback to React to an Operation

Get Native Mobile Development now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.