3

I'm new to Android Architecture Components / MVVM and would like to know what's the best way to implement communication between views.

So let's say I have A_View, A_View_Model, B_View and B_View_Model classes. As the user is interacting with A_View I need to update B_View (display a new image for example). Is it ok for A_View to get reference to B_View_Model and call a method that would trigger a LiveData causing B_View to update? To generalize the question, is it ok for a View to access other ViewModels to communicate with other Views?

Google's fragment communication example uses a "common" ViewModel to communicate. Is this necessary? Can't I just use the View's own ViewModel?

Also how do you handle if you want to update multiple views. Do you create a Controller/Presenter that has references to multiple ViewModels and invoke them accordingly?

kotsen
  • 119
  • 1
  • 4
  • 2
    Whenever I learn a new architecture, platform, etc... I generally have to remind myself that *if all I have is a hammer, then everything looks like a nail.* That being said, if you're worried about coupling A with B or later on down the line with C, then you could always interject a communication channel between A and B, something along the lines of *Pub/Sub*. `A` publishes an event to the communication channel and `B` is registered as a listener on the channel. The channel can have many publishers and many subscribers. – James Poag Oct 11 '18 at 01:33

1 Answers1

1

If A and B are siblings, I would expect the parent to provide the viewModels for both and handle any interaction between them. Strictly speaking, the parent would do this via its own viewModel, having references to each of the child viewModels.

You could implement an interface in Parent_View_Model that A_View_Model triggers, notifying the parent to affect the appropriate response on B_View_Model.

If B is a subview of A, then the same pattern would hold true, just with A acting as the parent.

rhpekarek
  • 167
  • 9