Deliver notifications to subscribers by using notification centers’ publishers.
Many frameworks deliver asynchronous events to your app with the
Notification API. Your app may already have places where it receives and processes these notifications in callback methods or closures. For example, the following code uses
add to print a message every time an iOS device rotates to portrait orientation.
Migrate Notification-Handling Code to Use Combine
Using notification center callbacks and closures requires you to do all your work inside the callback method or closure. By migrating to Combine, you can use operators to perform common tasks like filtering.
To take advantage of Combine, use the
Notification to migrate your
NSNotification handling code to the Combine idiom. You create this publisher with the
publisher(for:, passing in the notification name in which you’re interested and a source object, if any.
Rewrite the above code in Combine as shown in the following listing. This code uses the default notification center to create a publisher for the
orientation notification. When the code receives notifications from this publisher, it applies a filter operator to only act on portrait orientation notifications, and prints a message.