Object with multiple delegates.
We are gradually migrating our monolith project into a modularized structure. where we have the main application with tons of modules. In which we recently faced a scenario where we need to delegate a change to the module as well main application as shown in the architecture diagram [ CallManagerDelegate ]. Let's see how we have fixed that scenario using a multicast delegate.
Multicast Delegate
A generic wrapper around yet another delegate protocol that allows you to provide an object with an array of delegates, instead of just one delegate.
In the multicast delegation approach, the delegating object can hold multiple delegate instances that conform to a certain protocol. Since the delegating class can notify multiple delegates at a time, the communication channel opens one too many broadcasting possibilities.
We preferred to use NSHashTable
to store delegates weak references to avoid retain cycles since the delegate protocols confirming AnyObject
CallManagerDelegate
Let’s create an interface with necessary addons that needed to be delegated back to an array of instances.
didChangeCallConnection
delegates a state of an ongoing call to BusinesslineModule as well as Main Application- An error can pop out at any stage of an active call. So we tried passing the exact error instead of converting it into our own.
CallManagerMulticastDelegate
Next, let's use a Composite design pattern to create a composite delegate that conforms to CallManagerDelegate
and broadcasts didChangeCallConnection
and didFailed
to its sub-delegates.
CallManager
Let's complete our CallManager
with multi-cast implementation. The changes that we needed only when accepting the delegate. As we have shown in the sample, the delegate should be wrapped into CallManagerMultiCastDelegate before it gets assigned.
Assigning module and main app instances as delegates for CallManager using multicast implementation.
Let’s Wrap.
With the help of the MultiCastDelegate pattern, we are able to delegate the changes that can happen on an active call to both modules as well the main application instead of native NotificationCenter’s multi-recipient approach. Hope this helps in your daily use cases as well.
I hope you enjoyed this article 😀. Please feel free to share, comment, and give some claps 👏👏. Stay tuned at this pace for more updates. Thanks for reading this.