ViewModel refetches data when fragment is recreated
In onActivityCreated()
, you are calling getData()
. In there, you have:
productsViewModel.setInput(productsFilters, 2)
This, in turn, changes the value of _input
in your ProductsViewModel
. And, every time that _input
changes, the getProducts
lambda expression will be evaluated, calling your repository.
So, every onActivityCreated()
call triggers a call to your repository.
I do not know enough about your app to tell you what you need to change. Here are some possibilities:
Switch from
onActivityCreated()
to other lifecycle methods.initViewModel()
could be called inonCreate()
, while the rest should be inonViewCreated()
.Reconsider your
getData()
implementation. Do you really need to callsetInput()
every time we navigate to this fragment? Or, should that be part ofinitViewModel()
and done once inonCreate()
? Or, sinceproductsFilters
does not seem to be tied to the fragment at all, shouldproductsFilters
and thesetInput()
call be part of theinit
block ofProductsViewModel
, so it only happens once?
One simple solution would be to change the ViewModelProvider owner from this to requireActivity() in this line of code:
ViewModelProviders.of(this, viewModelFactory).get(ProductsViewModel::class.java)
Therefore, as the activity is the owner of the viewmodel and the lifcycle of viewmodel attached to the activity not to the fragment, navigating between fragments within the activity won't recreated the viewmodel.