ViewPager with viewmodel and live data , all 6 tabs data is replaced by last tab data
This should be happening due to your ViewModel
.
Typically, there's one ViewModel
per Activity
or Fragment
, due to the way a ViewModel
is designed to work. One of the major benefits in using a ViewModel
is that it's lifecycle is completely separate from the lifecycle of your Fragment
, therefore, your Fragment
can be destroyed and recreated multiple times and you'll still be able to restore current data that's stored in your ViewModel
.
Therefore, this means that with the typical code to fetch the ViewModel
from the ViewModelProviders
, you'll be fetching the exact same ViewModel
.
Typically, this won't cause a problem, but in your ViewPager
, you're reusing the same TimesListFragment
which is most likely calling up the same ViewModel
, therefore causing each fragment to show the same data.
The solution for this is to use:
ViewModelProviders.of(this).get(KEY, TimesViewModel::class.java)
Note the KEY which is used to differentiate between the ViewModels that needs to be fetched. So by using the positions in the ViewPager
as a unique key, you should be able to have a unique ViewModel
for each TimesListFragment
.