Reputation: 119
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?
Upvotes: 3
Views: 542
Reputation: 549
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.
Upvotes: 1