Dev Journal #11 - Model View ViewModel (MVVM)android
I took a long hiatus on this project due to a more pressing project at work. I think it turned out to be for the better. I gained a deeper understanding of full-stack development and despite having worked on a different framework, I should still be able to apply the same underlying principles that I have learned from my work. After abandoning the android project for over a year, I had to upgrade a lot of dependencies. In the process of doing so, I decided to migrate it to AndroidX from the original Android Support Library which is no longer maintained. I was pleasantly surprised by how much easier it became to develop in the new architecture pattern.
Model-View-ViewModel (MVVM) is a design pattern that allows the separation of the UI from the backend logic from the development standpoint. It is used widely in modern web applications that are built with state management libraries based on the Flux pattern such as Vuex and Redux. It is also a highly recommended app architecture for building an Android app supported with toolsets such as the Jetpack for an easier development experience.
View is represented by Activities or Fragments whose job is to inflate the layouts defined in the XML files and observe the binded LiveData objects' state to control the UI elements or respond to navigation actions.
ViewModel provides data for the View by fetching them from the repository. The ViewModel doesn’t know about UI components. ViewModel can access the Fragment arguments through the SavedState module. The key-value map SavedStateHandle allows you to write and retrieve objects from the saved state. Then the observable data holder LiveData component informs the Fragment when the data object is obtained.
Model’s role is to store the state of the App and provide the information to the ViewModel. Android documentation recommends using the Repository Pattern to isolate the data from the rest of the app. Repository can handle the logic to provide data from local database or external API.