preface

A collection of industry-renowned architecture articles. Get some architectural thoughts from your knowledge of architecture, and restructure Jetpack MVVM with architectural design principles and purposes! Github will continue to update this project and improve all the features of wanAndorid. I will also use 23 design patterns to practice in projects and thoroughly understand the use of design patterns in business scenarios. Welcome to pay attention

Github:github.com/blindmonk/W…

What is architecture

1.1 Architecture Introduction

What exactly is architecture? How to better understand architecture. We know that The Chinese language is extensive and profound and we can understand its meaning from its composition. Architecture is no exception. “Architecture” consists of “frame” and “structure”.

Frame: build, set up, support. Abbreviation: integral structure: houses, wood, brick and tile structures for people to live in. Abbreviation: Component

The combination of the overall structure and components forms the architecture. Taking the Android architecture as an example, an APP is usually composed of classes, and how these classes are combined and interact with each other is the key point that affects the APP itself. Subdivided into classes, interfaces (connectors), and task flows. Classes are the core “bricks and mortar” of an architecture, and interfaces are the paths, mechanisms, and expected results of communication between these classes. A task flow describes how the system uses classes and interfaces to fulfill a requirement such as a network request. As mentioned in the architecture introduction above, the house, wood and brick are connected with each other.

1.2 architecture

The concept of software architecture was designed in the 1960s and became popular in the 1990s. The history of computers started in the 1950s and the history of architecture is very short, and construction has been going on since the Stone Age. Human beings have accumulated a lot of experience and lessons in thousands of years of architectural design practice. Architectural design basically contains two points, one is architectural style, the other is architectural mode. Unique architectural style and properly chosen architectural pattern can make it a unique building.

The picture below shows the ancient Mayan architecture, chichen-Itza, with nine huge stone steps piled up, ninety-one steps (symbolizing the number of days in the four seasons) leading up to it, and a temple at the top of the tower rising into the sky. All the numbers are calendar-like and bold. It’s hard to imagine that this is a Stone Age building.

Winston Churchill said, “We build buildings and buildings build us. The Chamber of the House of Commons is too narrow for all members of the House of Commons to sit facing the same way. They must sit on two sides.” Churchill believed that the British party system was born when MPS took their seats and chose people who shared their political views.

Second, the purpose of architecture design

Almost all software design ideas can be found in the vast history of architecture. Many people believe that “form must follow function” (do you agree with this view? Feel free to leave your thoughts in the comments). Good design has both form and function. Such as our Beijing daxing daxing international airport airport terminal as the core to extend from the air like a phoenix, wings to fly to terminal core area as the center, to the northeast, southeast, south, southwest, northwest direction of five out of the five refers to the corridor, to the airport in Beijing daxing international effort. This design extends from the center in all directions, making the distance from the terminal’s central point to the farthest gate only about 600 meters, and passengers can walk there in up to eight minutes.

Architectural design has a certain purpose, and software architecture design is the same. The purpose of software architecture can be roughly divided into scalability, customizable, scalable and maintainable:

1. Scalability * : * The APP must be able to maintain reasonable software performance while the number of UV/PV users increases rapidly. This is the only way to be safe in rapid zero-to-one requirements iterations.

2. Customization: The same software system may face different and diverse user groups, which need to be customized according to different user groups and market demands. For example, some functions in an APP are only available to certain users.

3. Scalability: As new technologies emerge, a software system should allow access to new technologies to extend the functionality and performance of the existing system.

4. Maintainability: The maintenance of software system includes two aspects, one is to fix existing bugs, the other is to develop new iterative requirements into the existing system. An easy to maintain system can effectively reduce labor and material resources.

3. Practice an APP: Play Android

In view of the above introduction to the architecture, I believe that it has gone from strange to familiar. But the most important thing is practice. The great Chairman MAO once said that if you want to know the taste of a pear, you have to taste it yourself. Therefore, we use wanAndoird open API to simply implement an APP and summarize the key points of the above architecture. The main function points are as follows:

  • The front page is a categorized list of popular articles
  • The project page mainly contains the complete project
  • Click on articles and projects to view details

I don’t know if there is any impression that the above mentioned architecture “form must follow function” of course, this is not the authoritative definition, can be used for reference. Whether form follows function or function follows form, we can understand this sentence with structural thinking. Architecture can be roughly divided into form and function, so we build wanAndroid project according to these two points successively.

3.1 Architecture – Form

The form itself consists of two parts. One is the external shape of things, and the other is the internal structure and combination. In fact, the two are the same. How the content is combined internally, it naturally has a certain shape of expression externally.

The first thing we see when we open the project is the directory structure of our project. A clearer and more concise directory structure can help us get started with the project more quickly. It is mainly divided into two parts: core module and business function module:

The core module mainly has the following responsibilities:

  • Dagger dependency injection processing.
  • Extended features: various utils.
  • Base-level abstractions: BaseActivity, BaseViewModel, etc
  • Third library processing, network exception processing, etc

Business function modules mainly have the following benefits:

  • High cohesion
  • Clear functional structure
  • modular
  • Function isolation and encapsulation

Core and Features are divided under the main APP. Business modules are aggregated under Features in the form of packages instead of being split in a modular way. The benefits of this are as follows:

  • Faster compilation speed
  • Reduce dependency conflicts for Maven libraries
  • Reuse of common functionality
  • The cohesion of the bag

It can be seen that we did not adopt the modular division based on business modules, because I once came into contact with a project that split more than 40 modules, so it can be imagined that the disadvantages of the project will be exposed once it is huge:

  • Compile a project for up to 7/8 minutes, and compile speed optimization can be * see my previous article (compile speed optimization)
  • The Moudle dependencies in the project are crisscrossed

Of course, I’m not against multi-module modularity, because every pattern has its pros and cons, and it depends on the business of the current project to decide which one to use. In addition, kotlin was used to write all the projects:

  • build.gradle.kts .ktsGradle is also something that officials like to make simpler
  • buildSrcTo deal withgradleRely on
3.2 Architecture – Functions

The business function points in Playing Android mainly include article and item acquisition, and most of these function points are inseparable from network request and callback processing. I’m not going to describe the difference between MVC, MVP, MVVM and how to choose, but I can say that no architectural pattern is best or optimal, only the one that best fits the current business is a good architecture. Right now, Google’s official preferred architecture is MVVM, so let’s focus on MVVM. For more details, see the application Architecture Guide in the documentation on the official website:

The MVVM architectural pattern meets the architectural design objectives described above, while also adhering to the officially given architectural principles, which are roughly two points as follows. It might not be easy to understand just by looking at these two definitions. Therefore, under the understanding of structured thinking, separation of concerns is to reasonably decompose complex problems, then study the sides of decomposition, and finally synthesize the overall solution. Therefore, we should not do business logic in activities or fragments, but divide function points into minimum optimal solutions, and finally combine them into an overall solution. For MVVM, we derive ViewModel, LiveData, Model, etc.

  • Separation of concernsThe code in an Activity or Fragment should be the logic that handles interface and operating system interactions. Keep these classes as lean as possible to avoid many life-cycle related problems.
  • Drive the interface through the modelA model is the component responsible for processing application data. They are independent of the View objects and application components in the application and are therefore independent of the application lifecycle and associated concerns

Each component in MVVM depends only on its next-level component such as Activity –>viewMoudle–>Repository. At this point you may be wondering, what about the callback of the network request if it is a one-way dependency? This brings up the concept of “responsive programming” in conjunction with liveData, which is internally observer mode and associated with view declaration cycles such as Activity, Fragment or Service. The benefits of using LiveData are as follows:

  • Memory leaks do not occurThe observer will bind to Lifecycle objects and clean up after its associated Lifecycle has been destroyed.
  • It does not crash when the Activity stopsIf the observer’s life cycle is inactive (such as returning an Activity in the stack), it will not receive any LiveData events.
  • You no longer need to handle the life cycle manuallyInterface components simply observe relevant data and do not stop or resume observation. LiveData automatically manages all of these operations because it can sense the associated lifecycle state changes as it observes.
3.3 UseCase

UseCase is a concept in the Clean architecture, which is mainly used to connect the UI to the data layer and also to switch IO. As you can see, Rxjava was abandoned in this project because it could have been replaced by Kotlin.

abstract class UseCase<out Type, in Params> where Type : Any {

  abstract suspend fun run(params: Params): Either<Failure, Type>{

  operator fun invoke(params: Params, onResult: (Either<Failure, Type>) -> Unit = {}) {
      val job = GlobalScope.async(Dispatchers.IO) { run(params) }
      GlobalScope.launch(Dispatchers.Main) { onResult(job.await()) }
  }

  class None
}
Copy the code
3.4 A complete network request process

  • The View:A network request is sent and subscribed, processing UI data.
  • The ViewModel:forView(Activity/Fragment) provides data and handles business logic.
  • LiveData: A data store class with a life-cycle observable, LiveData stored in the ViewModel
  • UseCases: Used to connect ViewModel and Model and update LiveData.
  • Model: Data can be retrieved from the network, database, or other apis

Four,

We can realize the definition from the schema theory to the practice process of believe that you have your own understanding and insight, but this is just a way of implementation, if the architecture in the architecture design purpose and principles of the case, you have a better way of practice or have any doubt points and architectural projects can meet in the comments section or making comments. I also have a question here in that you agree that form must follow function? Feel free to leave your comments.

In the future, this project will continue to update and improve all functions of wanAndorid. I will also use 23 design patterns to practice in the project and thoroughly understand the use of design patterns in business scenarios. Welcome to continue to pay attention. While other platforms such as back-end and front-end architecture are built in the same direction. But I do have a few suggestions:

  • Business decision Architecture
  • Don’t over design
  • Interface oriented programming
  • Form follows function
References:

Application architecture guide, CleanArchitecture, LiveData overview