A Better Pattern Than Notification Center in Swift
Remind The Notification Center
The Notification Center is a type of the observer pattern, similar to the delegation pattern which informs that an operation has been completed. Let’s say that we are in the payment view controller for user’s subscription and we need to update the profile screen to show the paid subscription badge and update some part of the home screen so this is an example of the operation that I said.
Those operations are triggered using NotificationCenter.default.post(notification:) method signature and of course we need to add the notification as observer using NotificationCenter.default.addObserver() method signature.
Cons Of The Notification Center Compared To Multicast Delegate
- Using The Notification Center can potentially causes the retain cycle if we don’t remove from the implemented object. However, Multicast Delegate is not. Because, it uses protocol definition and the weak hash table implementation.
- The Notification Center is not type safe. It depends on string implementation to seperate each other. Therefore, it can causes misspelled naming.
- The Notification Center causes performance overheading. Let’s think about the notification has been posted. After that, we can operate any heavy operation.
Implementation Multicast Delegate
Let’s create a class that stores delegates weakly to prevent any memory leak and add remove invoke methods.
Let’s think about we have the in app purchase screen that user pays the subscription and the user can show the content in multiple screens like the profile screen, library screen after its payment.
First of all, we need to define a protocol that notifies status changing.
After that, we create InAppPurchaseMulticast class to adding delegates using singleton pattern.
We need to conform InAppPurchaseManagerStatusChangingDelegate to the classes for the status changing.
After that, we add these classes to the multicast respectively.
When the in app purchase status has been changed, we invoke changeStatus for updating other screens UI.
As we can see, we used Multicast Delegate instead of Notification Center, citing cons on multiple screens from the real world app scenarios.
Thanks for reading!