Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Keep state of my View Model persistent across a user session in SwiftUI (MVVM)?

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!

like image 473
Khalil Hajji Avatar asked Nov 21 '25 12:11

Khalil Hajji


1 Answers

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.

like image 90
joforsell Avatar answered Nov 23 '25 01:11

joforsell