What solutions have been found to prevent rebuild ...
# multiplatform
j
What solutions have been found to prevent rebuild of viewmodels on the backstack in compose multiplatform?
p
There is no such thing as ViewModel and Backstack in Compose multiplatform. You might be referring to a specific navigation library that adds support to it. My advice is to ask in the library project repo better.
plus one 1
c
My personal opinion is that it’s better to consider ViewModels as ephemeral, able to be created/destroyed/recreated at any time. If you want data to persist when navigating through the backstack of your chosen navigation lib, keep it in another layer of the application (cached in the Repository layer, for example). Then every time the ViewModel is recreated, it’s re-fetching the data that was previously cached in the Repository layer
j
I have to disagree there, image the situation, fetch a list, scroll down, navigate to an item, then navigate back. In this case you don't want another list fetch or the list to be recreated and jump you to the top.
c
The list state isn’t typically kept in the ViewModel, it’s in the
LazyListState
which is part of the composition. So what you should really be looking for is a way to keep the composition active in the backstack, not the ViewModel. Keeping the composition active is what will retain the list state, your ViewModels, and any other
Saveables
.
j
In MVVM I generally keep the state of whats displayed on the screen in the ViewModel, but to be more precise I am looking for something that does the same
hiltviewmodel()
or Koin's
getViewModel()
, the recomposition still happens but the viewmodels aren't destroyed
c
So again, it’s a very specific way that the navigation lib would be managing its state with Compose, not a concern of the ViewModel itself. ViewModels are exactly that, a model for a view, and thus ViewModels shouldn’t really exist independent of a specific UI view. For example, a ViewModel kept alive in the backstack when its UI composition has been destroyed. That data should be kept somewhere that lives longer than the UI, like the Repository. This is just my opinion, but I’ve found over the years that a lot of problems arise when ViewModels are trying to do too much or stick around for too long. Keeping a cleaner separation where ViewModels are short-lived and longer-lived data lives elsewhere has really helped me maintain apps with fewer bugs
j
Let me give you simpler example, lets say you have a input field where you put your name, then below there is a button that navigates you to a terms and conditions screen, when I return back the input value is gone because the viewmodel was recreated, well I don't want that. Just checking if there are solutions around that solve it like in Native Android