Common app architecture
This is a common architecture diagram to build robust, production-quality apps.
- Activity and Fragments should be responsible for maintaining UI related code like click listeners, adapters, dialogs etc.
- ViewModel is responsible for managing the data for UI Components like an Activity or a Fragment. It also helps in surviving configuration change.
- Implement a repository layer as the single-point entry to your data. It should decide if the data is to be fetched from local database using Room or from REST API using Retrofit.
- To keep the logic minimal in Activities or Fragments and distribute responsibilities, add a usecase-domain layer if needed.
Android architecture components
Android architecture components are a collection of libraries that help you design robust and maintainable apps.
LiveData is a component that is an observable data holder. It helps your UI elements observe data for changes to ensure your UI matches your data state. Since LiveData is a lifecycle-aware component, you don’t have to do manual lifecycle handling. There is almost no memory leaks and crashes due to stopped activities unless it is implemented correctly.
- Create an instance of LiveData to hold any type of data.
2. Create an Observer which updates your UI.
3. Start to observe the LiveData
ViewModel is responsible for managing the data for UI layer and handles the communication with the rest of the application.
ViewModel is always created in association with Lifecycle passed to the ViewModelProvider. It is alive until Lifecycle destroyed permanently. When the owner is finished, ViewModel’s onCleared() is called automatically to clean up resources.
a ViewModel will not be destroyed if its owner is destroyed for a configuration change (e.g. rotation). The new instance of the owner will just re-connected to the existing ViewModel. [*]
dos and don’ts
- ViewModel should never access view hierarchy or hold a reference back to the Activity or the Fragment.
- ViewModel should not contain android.* imports
- Use LiveData only to communicate between ViewModels and Views.
- Use view state classes to handle your application loading, sucess and error states.
- Distribute responsibilities, add a domain layer, add a data repository layer.
If you are interested in the topic, feel free to subscribe or to follow me on Twitter! If you like the article, feel free to share it.