Ofek Regev
Ofek Regev

Reputation: 502

How to use data from one ViewModel in another ViewModel

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.

Upvotes: 12

Views: 12022

Answers (2)

SlowLearnah
SlowLearnah

Reputation: 80

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. 

}

Upvotes: 3

murad
murad

Reputation: 61

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.

Upvotes: 1

Related Questions