I have an AddressesViewModel which holds the user's favorite addresses and another SearchViewModel which holds searched addresses. when user searched an address I have to check whether this address is favorite or not by checking in the favorites array. what is the proper way to do it?
I've already tried subscribing to the AddressesViewModel from the SearchViewModel but I'm looking for other options as it's creating too much dependency between those view models.
It is perfectly right to have ViewModel contains ViewModel. Actually that is the recommended practice: To have one main ViewModel for the whole page, the main ViewModel could contain ViewModels for the sub views in the page.
In android, we can use ViewModel to share data between various fragments or activities by sharing the same ViewModel among all the fragments and they can access everything defined in the ViewModel. This is one way to have communication between fragments or activities.
In fact you can have multiple view models for a single fragments doing different things for you. Keeping everything in one view model would make testing harder and also you have to keep viewmodel for all 20 fragments may be scoping to activity.
Another alternative if I understand the question correctly. Assuming that you first have this:
ViewModelChild(constructor etc) : ViewModelParent(){
// you can create a var/val to observe a variable in viewmodel parent.
// upon observation of
//this you can change other variables assigned here.
}
You will have to attach two ViewModels to the same lifecycle owner. eg You have an activity named MainActivity
, two ViewModels named AddressesViewModel
and SearchViewModel
and you need to get a variable named address
for SearchViewModel
to AddressesViewModel
class MyActivity: AppCompactAvtivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
.
.
// Attach the ViewModels
val addressViewModel = ViewModelProviders.of(this).get(AddressesViewModel::class.java)
val searchViewModel = ViewModelProviders.of(this).get(SearchViewModel::class.java)
// Listen to address which is in SearchViewModel
searchViewModel.address.observe(this, Observer { address ->
// Send the variable to AddressesViewModel using a public method
val favOrNot addressViewModel.isAddressFavourite(address)
// or
addressViewModel.favouriteAddress = address
})
}
}
Hope this answers your question.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With