Android: “universal” activity reconstruction

preface

It's been a long time since I wrote this article on Android: how to write a "universal" activity. However, due to a lot of things recently, the plan to write a refactoring article has been ruthlessly delayed. I have a little spare time in these days to understand my mind.

In fact, we all know that Android: how to write a "universal" activity is just an introduction. In fact, what I really want to lead to is the MVP design pattern, because I recently used MVP as a project and I have some feelings about MVP, so I will use MVP to reconstruct the "universal" activity.

At the same time, some friends communicate MVP with me. They will be confused by what logic should be put in M, V and P in MVP? Will be confused by how to write m in MVP? Will be confused by an interface, how to refactor according to MVP? Will you be confused by whether the listview adapter should be placed in the m layer or the p layer?

I hope the explanation of this article can help you have a deeper understanding of MVP. Now let's move on to the topic.

Text content

This paper is divided into two parts:

The first part will deeply understand what MVP is and its benefits. The second part will explain how to use MVP to reconstruct the "universal" activity.

Show you about MVP

Any software is data centric. In order to interact with users, it is necessary to provide an interface to support users to add, delete, modify and query data.

Whether MVC, MVP or MVVM are always doing one thing: how to better solve the relationship between data and interface, so as to achieve lower coupling between data and interface, higher code reusability and better code testability.

The focus of this article is to explain MVP, so let's begin to understand how MVP organizes the relationship between data and interface. Let's start with the structure diagram of MVP.

MVP's face

Some online structure diagrams about MVP are basically the following

MVP structure diagram.png

I think there is a problem with this diagram. The problem is that the presenter forwards the request to the model, and the model should return the processing result to the presenter. This diagram does not reflect this process.

The correct MVP structure diagram is like this

MVP structure

Let's see what we can get from this picture first?

After looking at the overall structure diagram of MVP, we introduce model, presenter and view in order from the bottom to the top.

model

First, let's talk about some misunderstandings about model:

We will see the correct understanding of model in the article.

Data processing plant

Through the experience after applying MVP, I personally feel that model is the most difficult to write and understand, because model is the data processing plant of the whole application or interface. The so-called data processing plant is the operation of data acquisition, data analysis, data storage, data distribution, data addition, deletion, modification and query. It means that all data operations are carried out in the model, so the model is not only a collection of entity classes, but also contains various data processing operations.

Three data sources

There are three data sources of data: memory, disk (file or database, etc.) and network. In order to improve the performance of app, it is necessary to temporarily store frequently accessed data in memory; At the same time, in order to improve app performance and save traffic and power for users, it is necessary to store data in disk; Other data is necessary to read from the network. The three data sources do not necessarily exist at the same time. For example, an app that does not interact with the network does not exist. Therefore, all codes related to the processing of data from three data sources should be placed in the model.

Model provides services for the upper layer

From the black box perspective, there are only two kinds of services provided by model for the upper layer (referring to the layer dependent on model, such as present): model provides data for the upper layer, and model processes the data transmitted by the upper layer

Model provides data for the upper layer

The upper layer will remove data from the model, and the model will take data from the three data sources in the following order

The above data retrieval process is the simplest case. More complex will also involve whether the data retrieved from memory or disk is expired. If it is expired, it should be obtained from the network. After obtaining data from the network, you need to update the data in memory or disk.

Model handles the data transmitted by the upper layer

After the model receives the data transmitted from the upper layer, the model will successively throw the data to three data sources for processing. It is possible that all three data sources will process the data, or it may be only one of them, and the model will return the processing results.

Therefore, the model will provide the parsed data to the upper layer. The upper layer is completely transparent to the source of the data. The upper layer does not need to care whether the data comes from memory, disk or even the network. Similarly, the upper layer only needs to throw the data to the model, and the only thing the upper layer can do is happily wait for the processing results.

tip

The model in MVC interacts with the view, while the model in MVP does not know any details of the view.

All operations in the model occur in normal threads.

This is the introduction to model. Let's take a look at the presenter.

presenter

Presenter translated into Chinese means host and presenter. From its meaning, we can see that it has the function of controlling the whole audience. First of all, presenter is in the middle layer of MVP and plays a connecting role in view and model. The presenter will give the commands given by the view to itself for certain verification and other operations to the model for processing, and will give the results of model processing to the view.

Presenter encapsulation service

Presenter not only acts as a bridge, but also covers the business logic code. In this way, the burden of activity can be reduced and the activity can do its work wholeheartedly. It is estimated that some friends are confused. What codes belong to business logic? For example, some verification codes. Or you can think like this. As long as the code does not belong to view and model, it can basically be placed in the presenter.

The presenter is responsible for refreshing the view

MVC or the previous writing method of view is generally like this. After receiving the data, the view refreshes or performs other operations by itself. However, the presenter in MVP is responsible for refreshing the view, such as the data obtained from the model. The presenter will notify the view whether to display the success interface or the failure interface according to the success of the obtained data. In this way, the activity becomes lighter and becomes a fool who listens to other people's commands. At this time, the presenter has the smell of host and controller.

Thread held by presenter

In Android, the operation of view needs to be executed in the UI thread, and other time-consuming operations need to be executed in ordinary threads. Presenter will hold two kinds of threads: UI thread and normal thread. When refreshing the view, it switches to the UI thread for refreshing, and switches to the normal thread for fetching data from the model. If you use rxjava, it is particularly simple about thread switching.

tip

The data obtained by the presenter from the model is the parsed data, and there is no need for the code to parse the data.

Then let's take a look at the view.

view

The view layer is easy to understand. It is the interface directly seen by the user. The view in MVP is very worry free, such as updating the view and receiving data. It doesn't need to worry about these operations. It doesn't need to know where the data comes from and what I show to me.

A view can have multiple presenters or only one presenter at the same time.

The activities and fragments in Android are used as views in MVP. The responsibilities of these activities and fragments are small. It is enough to only care about things related to the interface.

Various adapters are placed in the view layer.

summary

We have a preliminary understanding of MVP, what the model, present and view in MVP are and what the relationship between them is. This is just a preliminary understanding of MVP. There are still many details to be introduced in MVP. For example, in Android clean architecture, there is an additional layer of interactor between model and presenter, what the multiple layers of interactors are used to do, and how the model layer is structured. Google mvpmodel layer is simpler than Android clean architecture. I hope to see the detailed introduction of each layer in the following chapters. We began to enter the part of our refactoring "universal" activity.

Refactoring "universal" activity using MVP design pattern

Recall the "universal" activity

I added the login dialog function based on the "universal" loginactivity in the previous article. The code of "universal" loginactivity is as follows:

After recalling the code of "universal" loginactivity, we began to refactor.

Start refactoring

model

When using MVP, I usually have a habit of writing code in the order of model - > presenter - > view, so the reconstruction of "universal" loginactivity also starts with model. In the first half, we introduced the model. From the perspective of black box, the model has only two functions: one is output data and the other is input data. Therefore, during login, the presenter only needs to give the account and password to the model. The only thing the presenter can do is to monitor the login status. The model will give the account and password passed by the presenter to the server. The model parses the data returned by the server, stores it in disk or memory, and passes the parsed data to the presenter. Let's look at the pseudo code:

The login model layer is not as complex as what we do. For example, the user information returned by the server is stored in memory, the token returned by the server is stored in disk, and the automatic login function is realized. This example is only a very simple login function. In practical application, many things need to be considered for login. The login module layer is reconstructed here.

presenter

The presenter mentioned above is used to connect the view and the model. The presenter encapsulates the business. The presenter is responsible for refreshing the view.

Let's sort out what functions the presenter should include:

Let's start writing code. I refer to the presenter class organization structure of Google MVP for the class organization structure of presenter layer, because I think the class structure of Google MVP presenter is clearer. Let's look at the pseudo code:

The pseudo codes of the presenter layer logged in above are all key codes. Let's see what the above codes have done?

view

The view layer is very simple. You just need to establish the infrastructure and directly look at the pseudo code:

When the infrastructure is OK, it's time to refactor the "universal" loginactivity.

Let's focus on infrastructure baseactivity:

Because an activity may contain multiple presenters, it is necessary to collect these presenters in baseactivity.

You need to call the corresponding periodic method of each presenter in the lifecycle method of baseactivity.

Is the reconstructed loginactivity refreshing and only retains the logic related to the view.

Summary: the reconstructed class structure

This is the end of reconstructing the "universal" loginactivity. Let's summarize the reconstructed class structure:

Reconstruction perception

doubt

It is estimated that careful friends will find that the model layer is loginmanager instead of using repository in the model layer of Android clean architecture. Personally, I don't think it is necessary for the model layer to organize the class structure so strictly according to the repository architecture. Because the login function in this example is too simple, we use the simplest loginmanager class for the upper layer to call.

Advantages and disadvantages

After refactoring the "universal" activity with MVP, the following benefits are brought:

But it also brings some disadvantages. For example, there are many more classes created, and the cost of managing these classes will increase. But everything has two sides, depending on the size of the advantages and disadvantages. Personally, I think the advantages of MVP certainly outweigh the disadvantages, so it is necessary to use this architecture to design your app.

Improve production efficiency

In the above pseudo code, I do not use rxjava and dagger2. If they are applied to MVP, you will get twice the result with half the effort. Rxjava can make the interaction between presenter and model easier when writing presenter layer and model layer, and the model layer can become particularly simple, such as the operation of fetching data from three major data sources, It's OK for us to implement it in code, but it takes a lot of time, but it's easy to do it with some operators of rxjava. Dagger2 can better help you with dependency injection, and the famous retrofit can also improve efficiency.

summary

In this article, we have learned about MVP and each layer, and how to use MVP to reconstruct the "universal" activity. In fact, there are many things to pay attention to in each layer. For example, the model layer is the most difficult layer to write.

The above is the whole content of this article. I hope the content of this article can bring some help to your study or work. At the same time, I also hope to support a lot of programming tips!

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>