How to make ViewModels communicate with same Model if I shouldn't in MVVM create Model in View?

77 views Asked by At

Say, I have two Views. One is button, second is textView. When I click button, something changes in text. If I make it in MVVM, probably it should look like this: There are button and text view which have no kinda logic. Button calls ButtonViewModel onClick() when it's clicked, textView observes TextViewModel's liveData text. In both ViewModels no app logic, just providing click event to model and updating text. So, as I understand, they should communicate with the same Model, like ClickHandler:

Example scheme of communication

But I don't understand one thing. If I initialize ClickHandlerin ButtonViewModel, then TextViewModel will not know about it so TextViewModel will not be able to observe text update. Well, then I guess I need to initialize Model out of ViewModels and just provide it to them. Something like it:

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val clickHandler = ClickHandler()
        textViewModel = ViewModelProvider(this,ViewModelFactory(clickHandler)).get(TextViewModel::class.java)
        buttonViewModel = ViewModelProvider(this,ButtonModelFactory(clickHandler)).get(ButtonViewModel::class.java)

    }
}

But as I understand, initializing model ClickHandler in activity is against MVVM pattern - view shouldn't know about models.

I was trying to ask chatGPT for solutions, but it just confused me. One of solutions was dependency injection framework but I don't yet know about it, I guess "true" MVVM should work in android without such frameworks.

And yes, I simplified model part because there could be several models like ClickHandler and Text and they could communicate with each other, but probably it wouldn't change the problem because the models still should know about each other, so the chain of calls just becomes longer than on picture.

So my question is: How and where, using the MVVM pattern, should I initialize the models so that they close the chain of two views?

2

There are 2 answers

4
Anna Andreeva Rogotulka On

If your TextView and Button belong in the same Fragment, you should create a single ViewModel for that Fragment. All the UI logic will happen in that ViewModel, including click handlers.

0
Bruno Lima On

I think you should separate it two files:

  • ViewHolder that binds views to data in ViewModel
  • ViewModel that has your class with data objects

If you need any lifecycle awareness it should be in a ViewModel connected to the fragment or acvitity that you ware using.