Search code examples
android-studiokotlinviewmodel

Implementing a ViewModel for entire the application


I want to build a viewModel for entire the application to send and receive data between multiple fragments and activities. so, how can I do that


Solution

  • Do not implement ViewModel scoped to the application

    From Wikipedia article:

    The viewmodel of MVVM is a value converter, meaning the viewmodel is responsible for exposing (converting) the data objects from the model in such a way that objects are easily managed and presented. In this respect, the viewmodel is more model than view, and handles most if not all of the view's display logic. The viewmodel may implement a mediator pattern, organizing access to the back-end logic around the set of use cases supported by the view.

    From ViewModel class documentation:

    ViewModel is a class that is responsible for preparing and managing the data for an Activity or a Fragment. It also handles the communication of the Activity / Fragment with the rest of the application (e.g. calling the business logic classes).

    A ViewModel is always created in association with a scope (a fragment or an activity) and will be retained as long as the scope is alive.

    ViewModel's only responsibility is to manage the data for the UI.

    It's clearly defined that ViewModel is a binder between View and Model and nothing more. Currently only Activity, Fragment and their subclasses implement ViewModelStoreOwner interface allowing ViewModel be scoped to them.

    Also Application scoped ViewModel violate the important SOLID principle - Interface segregation (ISP). It states following:

    ISP splits interfaces that are very large into smaller and more specific ones so that clients will only have to know about the methods that are of interest to them. Such shrunken interfaces are also called role interfaces. ISP is intended to keep a system decoupled and thus easier to refactor, change, and redeploy.

    How to send and receive data between activities and fragments?

    Some ways to communicate easier than application ViewModel: