background

In Android development, we often face the following problems: (1) It is difficult to manage the life cycle of applications (activities and fragments), especially the life cycle management problems caused by the jump of fragments. (2) When the Activity needs to be re-created, the data stored in the interface controller (View layer) is lost and needs to be re-initialized, affecting the user experience. (3) Android asynchronous operation (DB, NetWork), after the interface controller (View layer) is destroyed, the interface controller needs to end the subscription relationship with the task, to avoid memory leakage and unnecessary information callback. (4) Android background services and tasks are becoming more difficult. This is mainly due to Android’s DOZE power-saving mode and later restrictions on background tasks and services. (5) local storage of user preference Settings and network request data.

To address the above problems, Google launched the Android Jetpack framework to solve the above problems. Jetpack is divided into four main sections (figure below) : foundation, Architecture, Behavior, and interface.

Advantages of using Android Jetpack components: (1) Lifecycles makes it easy to manage your application’s life cycle. (2) LiveData builds observable data objects to notify the view when the underlying data changes. (3) ViewModel stores UI-related data that is not destroyed in the application rotation and restores the data after the interface is rebuilt. (4) Room can easily implement SQLite database. (5) The WorkManager system automatically schedules the execution of background tasks to optimize the performance. (6) Navigation components can easily manage page jumps such as fragments.

(1) Managing data sources by defining Repository (Model). (2) Update the LiveData driven interface (View). (3) Use ViewModel instead of Presenter management data (VM) (4) Room (Sqlite) stores locally serialized data, and Retrofit obtains data from remote data.

Questions about the architecture: is the pattern MVP or MVVM architecture?

The MVP architecture has the following advantages over the traditional MVP architecture: (1) In the MVP architecture, Presenter holds a reference to the View layer, and there is a risk of memory leaks if the lifecycle is not handled properly. In the MVVM architecture, the View layer and VM layer communicate through LiveData, avoiding memory leaks. (2) The traditional MVP architecture, because the communication between layers is through interfaces, will lead to a surprising number of interfaces, appeals architecture through the Observer mode (LiveData) to avoid interface problems.

If you add Databidning to the appeal framework. Implementing a bidirectional binding of View and Model can evolve into an MVVM architecture. However, the DataBinding based MVVM architecture has the following disadvantages: (1) Data bidirectional binding, resulting in the View is not reusable. (2) implementing DataBinding through DataBinding will increase the difficulty of Bug debugging. (3) The complexity of business will bring about the complexity of View page and the code of Model layer will also increase.

Jetpack architecture

2.1 Lifecycles

  1. Lifecycles is a class that holds Activity and Fragment information for components that solve lifecycle management problems. Lifecycles source code analysis address
  2. Life cycle transformation diagram:
  3. Implementation Principle (1) Data structure: Why use this data structure? The SafeIterableMap has the following advantages: 1. The insertion operation of SafeIterableMap is time complexity O(1). Data is directly inserted by pointer movement and no hash algorithm is required. 2. Through the process of removing elements without triggering ConcurrentModifiedException. 3. Using a bidirectional linked list for storage saves memory space compared to a HashMap (Java 8 red-black tree).

    (2) Class diagram

  4. Lifecycle component members Lifecycle is defined as abstract classes, LifecycleOwner and LifecycleObserver are defined as interfaces.
  5. The component implements the LifecycleOwner interface, which has only a method getLifecyle() that returns Lifecycle objects: LifecycleRegistry.
  6. Lifecycle’s inner class State indicates the State and Event indicates the Event
  7. The member variable GenericLifecycleObserver of ObserverWithState inherits from LifecycleObserver

2.2 the ViewModel

  1. The ViewModel stores and manages uI-related data, ensuring that historical data can be recovered when activities are recreated. ViewModel source code analysis address
  2. Life cycle transformation diagram:
  3. The implementation principle onRetainNonConfigurationInstance (1) method. When the screen switchover occurs, the system calls the message along with the message. This method preserves Activity data and state just as onSaveInstanceState() does, except that it returns an Object containing stateful information, which can even contain the Activity Instance itself. After saving the Activity State with this method. (2) through getLastNonConfigurationInstance () in the new Activity to restore the original state of the Instance. For example: in the back window, we can not use onRestoreInstanceState, and instead of getLastNonConfigurationInstance method.

2.3 LiveData

  1. LiveData is a class that holds data objects and listens for changes to the data by registering a listener Observer. The biggest advantage of LiveData: LiveData is a component that senses the life cycle of activities, fragments, etc. LiveData source analysis address
  2. Implementation Principle (1) LifecycleOwner’s Observe () method is used to attach the observer object to the LiveData object, and the observer is subscribed to the LiveData object to notify the changes of data in the LiveData. (2) When Lifecycle is not active, the Observer is not notified, and even if data changes, an Observer that is not active is not notified. Lifecycle will also be deleted automatically without user manual cleanup. Avoid memory leaks: The Observer is bound to Lifecycle, which is aware of the Lifecycle of the component, so when Lifecycle is destroyed the Observer is automatically removed to avoid internal leaks.

2.4 the WorkManager

  1. WorkManager is responsible for managing background tasks. It is suitable for tasks that need to ensure that the system will run even if the application exits. WorkManager selects the appropriate way to run tasks based on factors such as device API level and application state. [WorkManager](juejin.cn/post/684490…
  2. Implementation principle architecture diagram:

2.5 Navigation

  1. Navigation manages APP page jumps. Navigation is mostly used in fragments. Using Navigation to switch fragments can make the code simple and intuitive. The Navigation component also supports Fragment, Activity, Navigation and subgraph, custom target, etc. Navigation source code analysis address
  2. Implementation principle class diagram:

2.6 Paging&Room

  1. Paging is mainly used in combination with RecyclerView, which is a Paging load solution. In this way, Paging only loads a part of the total data at a time. Room is an ORM library provided by Google. Paging&Room combined use

  2. Realization principle Schematic diagram:

The sample

Summary of JetPack-based architecture diagram:

Official website analysis: Address Repository modules handle data operations. They provide a clean API so that the rest of the app can retrieve this data easily. They know where to get the data from and what API calls to make when data is updated. You can consider repositories to be mediators between different data sources, such as persistent models, web services, and caches.

General awareness:

The warehouse module handles data operations and provides a clean API to make retrieving data easier. The warehouse layer knows where to get the data from and the API to call when updating the data. You can think of the repository layer as acting as an intermediary between non-passable data sources, such as persistence models, Web services, caches, and so on.

Conclusion: Following the separation of concerns principle through the Repository mediation layer eliminates the need for a specific data source for the ViewModel so that it can be swapped to other implementations as needed.