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 in onCreate(), while the rest should be in onViewCreated().

  • Reconsider your getData() implementation. Do you really need to call setInput() every time we navigate to this fragment? Or, should that be part of initViewModel() and done once in onCreate()? Or, since productsFilters does not seem to be tied to the fragment at all, should productsFilters and the setInput() call be part of the init block of ProductsViewModel, 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.