Multiple view models when sharing data between fragments?

Viewed 226

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?

1 Answers

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

Related