3

Let's say I have DashboadFragment which has its own ViewModel named DashboadViewModel. I have created separate layout for AutoCompleteTextView which is included in fragment_dashboard.xml file. I have created separate ViewModel for AutoCompleteTextView which is AutoCompleteTextViewViewModel. So here I have tried to observe the data which are typing in AutoCompleteTextView into DashboardFragment but it didn't worked.

I have recently started development in MVVM Pattern.

ravi
  • 899
  • 8
  • 31
Malay
  • 71
  • 9
  • In your scenario please do not create view models of such atomicity - just operate with hosting fragment's view model. – ror Dec 06 '19 at 20:59
  • Yes but actually, its common layout and used in whole application. So I have to create common ViewModel so it can be usable with other fragment's ViewModel. – Malay Dec 10 '19 at 12:42
  • It makes sense for composability, as is your use-case. Let's not forget that a ViewModel is just a headless Fragment working to help neaten code and make business logic probable for testing. A ViewModel with the same lifecycle could theoretically hold reference to another with the exact same lifecycle without any problem (though I'd avoid tight-coupling like that). Please provide more code regarding your specific problem, it can work it just depends how you went about it. – straya Nov 09 '20 at 02:59

1 Answers1

0

You can pass data between Fragment using the delegate viewModels

private val viewModel: ListViewModel by viewModels({requireParentFragment()})

it does mean that you will have in your dashboardFragment a AutoCompleteTextViewViewModel.

Another solution will be to use the setFragmentResult()API

See https://developer.android.com/guide/fragments/communicate#share_data_between_a_parent_and_child_fragment and https://developer.android.com/guide/fragments/communicate#fragment-result for more informations

achirat
  • 1
  • 1