Question

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?

Était-ce utile?

La solution

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.

Licencié sous: CC-BY-SA avec attribution
scroll top