Skip to content

Messaging

maculateConception edited this page Jun 20, 2021 · 7 revisions

Home  >  Developer reference  >  Messaging

The app uses a publish-subscribe messaging paradigm for app components and/or layers to communicate with each other in a loosely coupled manner.

Messenger class

All the app's messaging centers around the Messenger class. Messenger is a thin wrapper around NotificationCenter, providing publish-subscribe type functions and reducing the need for boilerplate code to extract payload objects from Notification objects.

Subscribe workflow

Messaging subscribe workflow image

Publish workflow

Messaging publish workflow image

Messenger code is cleaner

The advantage of using Messenger is clearly evident in the example code snippets shown below.

Notification handling using NotificationCenter

NotificationCenter.default.addObserver(self, selector: #selector(self.handler(_:)), name: .myNotifName, object: nil)

func handler(_ notification: Notification) {
    
    if let userInfo = notification.userInfo, let payload = userInfo["myObject"] as? MyNotificationPayload {
        // Do something with payload
    }
}

Notification handling using Messenger

Messenger.subscribe(self, name: .myNotifName, handler: self.handler(_:))

func handler(_ payload: MyNotificationPayload) {
    // Do something with payload
}

Notifications and commands

Aural Player defines 2 types of notifications:

Notifications

Notifications express that "something has happened", implying that message subscribers should respond to the event in some meaningful way. For example, when the Player detects that the playing track has completed, and the next track has begun playing, it notifies the Player UI of the track change. The Player UI will then refresh the Player view to display the new track info.

Notification example image

Notification payload objects are typically named XXXNotification, and they conform to the NotificationPayload protocol, so that Messenger can work with them.

Note that notification payloads can be of any arbitrary type, such as Float or String or any custom class / struct, and some notifications don't have an associated payload.

Commands

Commands are a special type of notification that express "do something". For example, when the MediaKeyHandler detects the user pressing the "Next Track" media key, it commands the Player to switch to the next track.

Command example image

Command notification payload objects are typically named XXXCommandNotification, and they conform to the NotificationPayload protocol, so that Messenger can work with them.

Like with regular notifications, payloads can be of any arbitrary type, or there may be no associated payload.

Clone this wiki locally