Home > Software engineering >  Send data between controllers with Notification and observers or protocols
Send data between controllers with Notification and observers or protocols

Time:09-12

In my app, I don't use Storyboard, and I have a coordinate class to start with the first view controller. And also I have a web socket manager class that connected to the coordinate class. So for example if the fifth View controller in hierarchy want to change something in the web socket class, I use event handlers or protocols to send data through each view controllers (for example here the forth VC get data and send it to the third, and then second and .. ) all the way down to the coordinate and it send it to the web socket manager. I can use another option to use Notification and observers to send data directly from the fifth view controller in hierarchy directly to websocket manager manager and when I get the call back, use Notification and observers again to send data from web socket to the fifth view controller in hierarchy.

I don't know which way is the most effective way in term of use less CPU and RAM and also most reliable way. Could you please tell me which way is better here? Thanks

CodePudding user response:

IMHO I don’t think it’s a good use case for Notifications, as you are just passing an event from one object to another. Notifications are more useful when you need to broadcast an event that multiple objects will observe.

On the other hand, if you inject the event handler to all view controllers down the hierarchy, that would be a good solution if all of them depend on the Websocket manager. But if it’s only used by the fifth view controller down, perhaps it is not a good idea either, as you are injecting an irrelevant dependency to several objects and that’s not scalable.

If that is the case, I think your best choice here would be to have your Websocket Manager as a singleton and inject it directly into the view controller that requires it. I’m not a big fan of singletons, to be honest, but they are handy in cases like this. You just need to be careful of how you use it if it holds any state that can be changed by multiple objects concurrently.

Here is an example of how you could use this approach:

class WebsocketManager {
    
    static let shared = WebsocketManager()
    
    private init() {
     
    }
}


class ViewController: UIViewController {
    
    let websocketManager: WebsocketManager
    
    init(websocketManager: WebsocketManager = .shared) {
        self.websocketManager = websocketManager
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

Hope it helps.

  • Related