-
Notifications
You must be signed in to change notification settings - Fork 48
Messaging
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.
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.
The advantage of using Messenger is clearly evident in the example code snippets shown below.
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
}
}
Messenger.subscribe(self, name: .myNotifName, handler: self.handler(_:))
func handler(_ payload: MyNotificationPayload) {
// Do something with payload
}
Aural Player defines 2 types of 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 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 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 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.