Reputation: 51
I am trying to implement an IOS App following the MVVM architecture. Everything works well when I don't need my state to be persistent as I move through views and navigate back.
However, when a user navigates two or three steps back to View, I want my view to appear the same way than when it was left. For this, my reasoning is that I need to make my ViewModels persistent and not have them disappear when the view gets destroyed. So far, they disappear because I create them when I instantiate the View.
My question is:
1- Is this the right way to think about it? (i.e keep my ViewModels persistent)
2- What is the standard way to achieve persistence of the viewModels within the MVVM framework?
For context (if useful): Currently my view hierarchy is implemented with Navigation Links
Thanks!
Upvotes: 3
Views: 1664
Reputation: 65
You can instantiate your viewmodel in the App struct (or somewhere else, like the first view a user encounters) then pass on that same instance of the viewmodel to deeper views. A common way to do this is by using @StateObject
to instantiate and pass it on as an environment object.
You pass the environment object once and then all views lower in the hierarchy gets access to it.
So @StateObject var viewModel = ViewModel()
in your App struct. Pass this viewModel to the first view in the hierarchy inside the WindowGroup like so:
ContentView()
.environmentObject(viewModel)
Now any views under ContentView in the hierarchy can access the viewModel instance through @EnvironmentObject var viewModel: ViewModel
.
Upvotes: 3