3

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!

  • 1
    Look into [SceneStorage](https://developer.apple.com/documentation/swiftui/scenestorage). Apple also has the [Restoring Your App’s State with SwiftUI](https://developer.apple.com/documentation/uikit/view_controllers/restoring_your_app_s_state_with_swiftui) code sample – lorem ipsum Jan 21 '22 at 00:47
  • You could use an observable object which is created in your app that you pass as environment object to subviews. – Ptit Xav Jan 21 '22 at 10:02

1 Answers1

2

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.

joforsell
  • 55
  • 6