Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ViewModels reinitialize after view changes #50

Open
guillevc opened this issue Mar 22, 2021 · 1 comment
Open

ViewModels reinitialize after view changes #50

guillevc opened this issue Mar 22, 2021 · 1 comment

Comments

@guillevc
Copy link

guillevc commented Mar 22, 2021

First of all, thanks for all the work put onto this project. I'm building a project based off of this and it's looking really good, but I am encountering some issues that I explain below.

To summarize:

ViewA navigates to ViewB. To achieve this, I implement a NavigationLink(destination: ViewB(viewModel: ViewBViewModel())). When inside ViewB, some app state is modified, which ViewA receives with a onReceive. In the onReceive callback, ViewA makes some changes to its view like disabling a button. This causes ViewA to recalculate itself, which initializes ViewBViewModel again, losing all the changes, including all loaded data from the repository, leaving the user on ViewB with all Loadable set to .notRequested, and all viewModel state lost.

This also happens if the app state is implemented through a EnvironmentObject. If I modify some environment object from ViewB that ViewA uses, ViewA recreates itself, losing all the state on ViewBViewModel.

I am also having some issues related to this when navigating back from a view to its predecessor. In some cases, if I navigate from some view ViewA to other view ViewB, when dismissing ViewB, ViewA gets recalculated, which initializes ViewBViewModel again.

Has anyone encountered this behaviour and came to a solution?

@guillevc
Copy link
Author

guillevc commented Mar 29, 2021

Using @StateObject instead of @ObservedObject for view-owned view models seems to stop views from recreating view models on every view refresh, even if some parent view is changing.

So it could be a potential improvement, at least it's keeping things in place for me.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant