I want to follow the MVVM app architecture. I also need to have some communication between some fragments. But the official approach is pretty confusing.

Taken from the docs (https://developer.android.com/training/basics/fragments/communicating): "The recommended way to communicate between fragments is to create a shared ViewModel object."

Now let's say we have 4 full screen fragments. The fragments need to communicate with eachother. So therefore, we have one shared ViewModel for 4 fragments. Let's say some of these fragments display some additional data from a different source. This means that the ViewModel needs to hold multiple repositories.

Summarizing, our app architecture would look like this:

image of inter-fragment communication

This results in a "God" viewmodel that from my point of view is just messy. However - as previously stated - this is the official approach. So my question is, doesn't this recommendation contradict the MVVM app architecture on so many levels? Isn't there a better solution?

  • This feels like a bit of a strawman. You should consider just small slivers that share common state to reside in shared vms. Other stuff should be in their own vms. There are lots of different ways to approach this and I don't think Android is advocating for God VMs – Alex Hart Aug 24 '19 at 2:26
  • I see. So I could have one small shared VM and several bigger independent VMs for the fragments? – Josip Domazet Aug 24 '19 at 13:51
  • This is what I would do in this case yes. Separation of Concerns – Alex Hart Aug 24 '19 at 13:52

It's really hard to say where do you draw the line between single and shared ViewModel usages.

As a rule of thumb, I would use shared ViewModel in the case and only in the case when two or more views create an inseparable logical unit, but because of the screen size, they are separated in multiple views.

For example, if you create some very long object, with lots of data, and this data doesn't fit nicely into one screen so you need two screens. This very long object needs data from both screens or it should not be created. In this case, if you have a shared view model it will save you from the headache of drafting inconsistent data in your local storage or transferring large parcellable objects.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.