Search code examples
androidandroid-fragmentsandroid-viewmodel

Android: One ViewModel for multiple Fragments possible?


I have a general question about App architecture with Android. I am implementing an App (in Java) that has a single activity and 20Fragments (that are similar but not the same). So far I implemented everything in the fragments (UI, Logic, Database queries). Now I am considering to use a ViewModel but I am not sure whether it is worth the effort. So my question is whether each of my 20 Fragments should have an own ViewModel or whether I can just implement one ViewModel for all the 20 Fragments? Implementing a ViewModel for all Fragment classes would drastically increase the effort, so I would like to know if it is possible to have only one ViewModel for all Fragments?


Solution

  • It is technically possible to have one ViewModel for all Fragments.

    However, since this one ViewModel would have to manage a number of very different use cases, it would be something like a god object. With 20 Fragments, it would have very many lines of code ...

    Switching over to MVVM is generally worth the effort becasue in the long run the app is easier to test and to maintain.

    It may be a good idea to have a BaseViewModel in your app: a ViewModel class which handles things which are similar in all use cases, like letting the Fragment know that it should show a loading indicator or an error message. The "normal" ViewModels could extend BaseViewModel and focus on their use cases.

    It makes sense in some cases to have a shared ViewModel, for example when a Fragment shows a dialog with some EditTexts or when one has workflow with a sequence of 3-4 Fragments on a small device where on a larger device one or two Fragments would suffice.

    Just in case, here's my favourite starting point for MVVM app architecture: Guide to app architecture