I was under the impression, that a ViewModel would preserve state and data between Fragment switches, as long as they belong to the same Activity. That does not seem to be the case.
My ViewModel:
public class MainViewModel extends AndroidViewModel {
public MainViewModel(@NonNull Application application) {
super(application);
Log.d("MainViewModel","constructor called");
}
}
Access in a fragment:
MainViewModel viewModel = new ViewModelProvider(this).get(MainViewModel.class);
I noticed that the constructor is called every time I request the ViewModel. I thought that the purpose of the ViewModel was to stay alive all this time and could be used to preserve some state between fragments. Am I doing this wrong? Was my expectation wrong? How can I preserve state between fragments?
The issue is that you are using a ViewModelProvider
that is scoped to the fragment instance rather than the parent activity instance. Replace new ViewModelProvider(this)
with new ViewModelProvider(requireActivity())
.
More info available in the documentation: https://developer.android.com/topic/libraries/architecture/viewmodel/viewmodel-apis#vm-api-any-owner