Search code examples
androidmvvmdata-bindingarchitectureandroid-viewpager

Android - MVVM with ViewPager


I'm trying to delevop my first project using MVVM pattern.
I have two fragments:

  1. MyViewCollection (fragment, which contains list of side-scrollable fragments).
  2. MyView (side-scrollable fragment).

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.

  • MyViewViewModel sends to View specific data to contain within fragment.
  • 'Watch Later' button located in MyViewCollection, because of reach beautifull static buttons over side-scrollable fragments.
  • When button is clicked from MyViewCollection, I must grab current data from MyView, and send it to Room.

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:

  1. It is good practice, when 'Views' in MVVM 'talk' with each other? (If not - how to avoid that in situations, like mine?).
  2. I know that best practice is write to Room from ViewModels, but ViewModels cant 'talk' with each other, and with Views. So how I must keep data from 'MyView', to write it to Room from 'MyViewCollectionViewModel' (not from 'MyViewViewModel')?

Solution

  • 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