I'm trying to delevop my first project using MVVM pattern.
I have two fragments:
Each of them has ViewModels, which using Data Binding with Live Data.
I have 'Watch later' button in MyViewCollection, which must save content from MyView to Room DB.
How I reach that.
MyView (Fragment):
Data currentData;
...
viewViewModel.getData().observe(this, data -> {
currentData = data;
...
}
MyViewCollection (FragmentCollection):
// on button clicked
viewCollectionViewModel.getIsDataToLoad().observe(this, aBoolean -> {
MyView fragment = (MyView) adapter.getFragmentActivity()
.getSupportFragmentManager()
.findFragmentByTag("f" + currentFragmentPos); // currentFramgentPos from onPageSelected (ViewPager2)
Data data = fragment.currentData;
// async task:
RepositoryDB.getRoomInstance().getDao().insertData(data);
}
So I have two questions:
best practice is to have two viewmodels in your MyView . second viewmodel is a sharedView model between all fragments including MyViewCollection. you can store data there and do your staffs. ReadMore about Shared ViewModels