Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Android MVVM Architecture

Android MVVM Architecture

Android Maestro

July 15, 2019
Tweet

More Decks by Android Maestro

Other Decks in Programming

Transcript

  1. | Course Objectives MOBILE APPLICATION DEVELOPMENT 2 At the end

    of this lecture, each student should: • Understand the meaning of Architecture of an app and its advantages. • Understand what are Google’s Architecture Components. • Understand the MVVM Android Architecture. • Understand using ROOM, Retrofit and Repositories in the Model layer of the MVVM Architecture. • Understand using ViewModels, Lifecycles, LiveData in the ViewModel layer of the MVVM Architecture. • Understand using DataBinding and ViewBinding in the View layer of the MVVM Architecture. • Understand how to connect the different layers using Dagger2
  2. | Android Architecture Components MOBILE APPLICATION DEVELOPMENT 3 Android architecture

    components are a collection of libraries that help you design robust, testable and maintainable apps. Why architecture matters? • Robustness- ability of an application to scale up well with addition of more features. • Maintainability- defined as the degree to which an application is understood, repaired or enhanced. How fast can you react to design changes? • Testability- degree to which application components can be tested easily and individually.
  3. | Current State 4 Bundling all UI logic and business

    logic into one activity or fragment class is not a good software practise. It results in what is referred to as spaghetti code. UI logic refers to code that handles user interactions e.g. click or swipe while business logic refers to code that performs core app functions e.g. fetching user data from a REST API or saving user input to a database. Writing UI logic and business logic in one class makes your code hard to maintain, test and even add more features. It goes against the first SOLID principle of single responsibility, i.e. a class should have one and only one responsibility. An activity or fragment should only handle UI logic.
  4. | Android MVVM Architecture MVVM is an android architecture that

    allows separation of UI logic from the business logic by using architecture components such as viewmodel, livedata and room. MVVM seeks to achieve the principle of separation of concerns. UI based classes such as Activity and Fragments should only contain logic that handles UI and operating system interactions. MVVM has three main layers: • Model- represents the data and business logic of the app (includes Room Components, Retrofit Service Classes and Repository) • ViewModel- middle component that acts as an interface between the view and model. It provides the view with relevant data to consume. Exposes streams of data through live data objects. • View- handles user interactions and informs the view model about user actions. Observes live data objects. 5
  5. | LiveData • LiveData is an observable data holder class

    that helps to achieve the observer pattern in android. Observer pattern is where an object has a list of observers or subscribers which are notified in case of any changes. • LiveData is lifecycle aware meaning it respects the lifecycle of other app components such as activities of fragments. This awareness ensures LiveData only updates app component observers that are in active lifecycle state i.e. STARTED or RESUMED state. • You can register an observer paired with an object that implements the LifecycleOwner interface. This allows the observer to be removed when the state of the corresponding lifecycle object changes to DESTROYED. 10
  6. | Advantages of LiveData • Ensures your UI matches your

    data state, observer pattern. • No memory leaks because observers are bound to lifecycle objects, memory clean up occurs when these objects are destroyed. • Always up to date data. An activity that was in the background receives the latest data right after it returns to the foreground. • Proper configuration changes. 11
  7. | Working with LiveData objects 1. Create an instance of

    LiveData to hold a certain type of data. This is usually done in the ViewModel class. Expose the livedata to the activity by using a getter method. 2. Create an Observer object that defines the onChanged() method, which controls what happens when the Livedata objects held change. This is normally created in a UI controller. 3. Attach the Observer object to the livedata object using observe() method. The observer() method takes a LifecycleOwner object.This subscribes the observer object to the livedata object so that it is notified of changes. When you update the value stored in the LiveData object, it triggers all registered observers as long as the attached LifecycleOwner is in active state. 12
  8. | Observe LiveData objects onCreate() method is the right place

    to begin observing LiveData object: • To ensure the system does not make redundant calls from an activity’s onResume() method. • To ensure an activity or fragment has data that it can display as soon as it becomes active. The observer only receives changes if the livedata object changes. 14
  9. | Update LiveData objects There are two different types of

    livedata: Mutable LiveData and Immutable LiveData i.e. LiveData<T>, mutable live data can be modified or updated even after initialization while immutable livedata objects cannot be updated. It is a good practise to expose immutable live data objects to the UI. MutableLiveData class exposes setValue(T) and postValue(T) methods publicly to edit the value stored in a LiveData object. 16
  10. | LiveData with Room The Room persistence library supports observable

    queries, which return LiveData objects. Observable queries are written as part of a DAO. Room generates all the necessary code to update the LiveData object when a database is updated. 17
  11. | View Model • A viewmodel acts as a communication

    center between the repository and UI. The view model is designed to provide data to the UI in a lifecycle conscious way and survive configuration changes such as screen rotations. • The Android Framework manages lifecycles of UI controllers such as activity and fragment meaning they are out of the control of the developer. The android framework may decide to destroy or recreate a UI controller in response to certain user actions. • If the system destroys or recreates a UI controller, any transient UI-related data you store in them is lost e.g. a configuration change. • One can use onSaveInstanceState() method and restore UI data from the bundle in onCreate() method however this approach is only suitable for small amounts of serializable data. 18
  12. | Implement a ViewModel Viewmodel is responsible for preparing data

    for the UI. Viewmodel objects are automatically retained during configuration changes so that the data they hold is automatically available for the next activity or fragment instance. 19
  13. | Use the ViewModel in your UI Controller 21 One

    ViewModel can be shared amongst multiple activities or fragments. NB: A viewmodel should not hold any reference to a view, because in case of any configuration changes the reference to the view will change therefore making the viewmodel’s reference obsolete.
  14. | Lifecycle of a ViewModel Viewmodel objects are scoped to

    the lifecycle passed to the ViewModelProvider when getting the ViewModel e.g. the lifecycle of an activity or fragment. The ViewModel remains in memory until the lifecycle it’s scoped to goes away permanently, e.g. when an activity is destroyed. 22
  15. | Data Binding There’s an imminent drawback of using findViewById()

    as the depth of your layout hierarchy increases. It’s also not safe because it’s not checked at compile time. Id the ID you pass to findViewById is wrong the app will crash at run time. Data Binding Library is a support library that allows you to bind UI components in your layouts to data sources in your app using a declarative format rather than programmatically. 24
  16. | The Model Holds the business logic and the data

    access layer of the application. Some of the components: • Database Layer - Provides persistence of data locally on the device. – SQLite Database is already installed. – We use ROOM together with SQLite Database which is a Persistence Library that eases the use of an SQLite database. • Network Layer - Provides connections to network services and remote data. We can access APIs provided by servers or we can connect to sockets for Bidirectional communication with remote services. – Retrofit provides an easy way of consuming RESTful APIs over an internet connection. • Repositories - Connects the different sources (databases,network endpoints, ...) of data together to provide a single DataSource – You can have multiple off them according to the usecase 28
  17. | Data Layer 29 • The Data Layer comprises of

    Data Sources. • An application retrieves and stores its data through the Data Layer.
  18. | ROOM Why ROOM? • Allows for Freedom. You can

    still define pure SQL code. • Easy Debugging. SQL code is verified at compile time. Except @RawQuery. • Less Code. Its an Object Relational Mapper (ORM) therefore you can easily define tables through objects instead of doing it manually using SQL. • Migrations. Allows easily making changes to your database even if the app is already in production (In use by users). • Easy Testing. Room provides testing helpers and alot of support. • Support. Supported by Google. Tones of features and intergrations to other frameworsks added. 30
  19. | ROOM’S Structure 3 Main Components • Entities – Describes

    the structure of a table. • Database Access Objects (DAOs) – Allows access to the database. – Holds methods of manipulating the database. • Database – Strings the Entities and DAOs of a database together for ROOM to understand. – Holds the a database connection. 31
  20. | Retrofit 35 • Is a Representational State Transfer (REST)

    client. • Works with HTTP and connects to HTTP API endpoints over a network. • Converts HTTP request to callable functions and the responses to objects through same conversion provided by converter. • To convert a JSON response to an object we can use a GSON converter. • For XML responses you can use Jackson / Simple XML converter. • Therefore, it makes requests to a remote service easier. You just define an interface and Retrofit will provide the implementation of making the network request. You don’t have to parse a response yourself, which comes back as a string of text.
  21. | Repository • Repositories acts as interface to the data

    layer. • ViewModel uses the repository to communicate to room database and retrofit service. • Repository consolidates data from different sources, e.g. GraphQL, Firebase, REST API and ROOM. • Each feature of the application has its own repository that knows where to get the relevant UI data. • The repository should not know about the view model. 38
  22. | Further Research • SOLID Principles • Kotlin • Clean

    Architecture • Dependency Injection e.g. Dagger • Unit Testing and Instrumentation Testing • Asynchronous Libraries e.g. Rx-Java and Coroutines for Kotlin • How to host your app on Play Store • Books to read: Pragmatic Programmer, Cracking the Coding Interview, Clean Coder, Clean Code. • @Android254 and DroidConKE 2019 40
  23. | Links to Useful Resources 1. https://proandroiddev.com/ 2. https://androidstudy.com/ 3.

    https://androidweekly.net/ 4. https://www.udacity.com/course/developing-android-apps-with-kotlin 5. https://github.com/JabezNzomo99 6. https://github.com/ErickNK 41
  24. | Ole Sangale Road, Madaraka Estate. PO Box 59857-00200, Nairobi,

    Kenya Tel: (+254) (0)703 034000/200/300 Fax : +254 (0)20 607498 Email: [email protected] Website: www.strathmore.edu