Reputation: 1145
My Swift project uses MVVM and I'm wondering what's a way of having a "ViewModel" for my AppDelegate, that could be accessed by all the other ViewControllers. I understand that the AppDelegate isn't really a ViewController to have its own ViewModel, if strictly following MVVM model all throughout the app.
I want to have a state for my whole app for when the user is logged out, downloading something, etc. Perhaps someday the "ViewModel" would have plenty more use.
Should I just have global variables for these statuses or is there a way I can have my AppDelegate have a viewModel
property, then let my ViewControllers access it? It just seems "less clean" for me having global objects that aren't constants (that's only what I feel).
I'm also using ReactiveCocoa 4, if that would be of any help.
Upvotes: 1
Views: 1441
Reputation: 311
Dependency injection would be the best approach, you can have a class that manages the App's routing and passes the shared objects down the hierarchy.
class ApplicationNavigator {
let loginManager = LoginManager()
init(window: UIWindow) {
let exampleViewModel = ExampleViewModel()
let exampleViewController = ExampleViewController(loginManager: LoginManager, viewModel: exampleViewModel)
let navigationController = UINavigationController(rootViewController: exampleViewController)
window.rootViewController = navigationController
window.makeKeyAndVisible()
}
}
Then in the AppDelegate didFinishLaunchingWithOptions
var navigator: ApplicationNavigator?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
window = UIWindow(frame: UIScreen.main.bounds)
navigator = ApplicationNavigator(window: window!)
return true
}
Upvotes: 0
Reputation: 201
While allowing the AppDelegate to be a catch all is a common pitfall to avoid I don't think a ViewModel for the AppDelegate is the best solution. An alternative solution would be to create a "manager" class (or struct) using a singleton that could store login state for the app. That way your login state would be accessible to the rest of the app without adding clutter to the AppDelegate.
Upvotes: 1