1

I have an activity with three fragments. All three fragments share a few pieces of data, but they each also have some data that is unique to their respective fragment.

I know it is common practice to use shared viewModels as referenced in the Google docs.

But my question is, how do I handle the data that is not shared between the fragments? Should I create another viewModel for each fragment, and have each fragment reference a shared viewModel as well as a viewModel that only has their own specific data, for a total of 4 viewModels? Or do I put everything in the shared viewModel and have each fragment only reference that?

yambo
  • 1,388
  • 1
  • 15
  • 34

1 Answers1

0

I think you need to create viewModel in Activity then call any api in ViewModel after that, api response you can use anywhere in fragments

Create ViewModel instance in Activity : SettingViewModel settingViewModel = ViewModelProviders.of(this).get(SettingViewModel::class.java)

you can use settingViewModel in any fragment but you need to typecast fragment reference (e.g requireActivity()) to your activity after that you can use api data in fragment

Sumit Kumar
  • 263
  • 1
  • 6
  • I'm not sure I fully understand. Are you saying to have a single viewModel for the activity, and update the fragments from that data? Would each fragment also have its own viewModel? – yambo Feb 10 '22 at 17:07
  • Yes I am saying you to create single viewModel in activity and then call api in viewModel so that all the data of api is in viewModel after that use viewModel in fragment no need to create multiple viewModel – Sumit Kumar Feb 11 '22 at 06:55
  • So, what happens now if I want to re-use just one of the fragments within another view? Do I have to carry this large ViewModel around everywhere? – yambo Feb 12 '22 at 04:26