How to use data from one ViewModel in another ViewModel
Asked Answered
R

2

12

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.

Reality answered 7/1, 2019 at 8:1 Comment(3)
See this example: developer.android.com/topic/libraries/architecture/… . Hope it helpSweep
Already looked into it. It demonstrates a way to communicate between two subjects not between two ViewModelsReality
you can extract the common logic for the favourite address into the usecase and use it in both the view models.Nucleoplasm
M
3

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. 

}
Merriott answered 18/9, 2020 at 4:5 Comment(1)
This is a wonderful solution, even to reduce the number of viewmodels is a nice aspect. but beware that creating this bound, all properties are shared ( respectively to the privacy modifiers ).Barbwire
I
1

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.

Iota answered 17/1, 2019 at 12:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.