The application of the Android-in-the-text MVVM tutorial

Source: Internet
Author: User

Background

The MVP architecture has been very popular in Android for the past few years and has become almost the mainstream framework, making business logic and UI operations relatively independent, making the code structure clearer.

MVVM in front of the fire is a mess, and on the Android side but basically did not see a few people in use, see the introduction of MVVM is also the most talk about DataBinding or introduce ideas. Occasionally see a few mentions of the application, or Google's official website of the architecture components of the translation.

I believe that when you look at other people's blogs or official documents, you will always encounter some pits. Either the introductory tutorial is too complicated to write (the inability to spit out the groove, the front to write a bunch of principles, all kinds of tall pictures, and then eggs, to practice part of a stroke, you sure is really an introductory tutorial). Either it's simply a Hello world, and then there's no more (see Want to curse).

I can't look down, I decided to meddle in your life.

Directory

The Android-in-the-text MVVM tutorial is divided into two parts: application, principle.
Adopt the gradual way, the content is in layman's language, conforms to the human learning law, hoped everybody uses the least time to master MVVM.

Application article:
"Hello MVVM" (Quick Start)
Repository (Data Warehouse)
Cached cache (local cache)
Lcee state (Load/empty/error/content View)
Simple data source
Load more (load more)
DataBinding (data and view bindings)
RxJava2
Dragger2
Abstract (abstraction)
Demo (example)
12-n TBD (Welcome to GitHub for suggestions)
Principle article
Mylivedata (The simplest livedata)
02-n to be determined (not to interpret the source code, so boring, is going to take you from 0 to a Architecture)
About questions

I have limited level and energy, if the big guy found out where to write wrong or have good suggestions, welcome to the GitHub Warehouse included in this tutorial to mention issue.
What? Why not leave a message on the blog? Considering the domestic reprint of the basic disregard of copyright situation, generally you are not in the source to see this article, so leave a message I also generally can not see.
Objective

Almost a year has not updated the Android technology stack, early this year found that Google is pushing Architecture. This is Google's launch of the rapid implementation of the MVVM architecture of the class library. Now is the RC version, the official version should not be far away. After experiencing such an architecture, you can only describe it in one word.

Although it is not intended to be a long-term Android development, but in its position, taking into account the development of the Android community, it is necessary to give everyone a rise in posture.

Thought

What is MVVM?

Very simple, Model (data) view (view) ViewModel (Data View manager)

Can you be more specific?

Model:bean (entity Class), Data Source (HTTP request-related, database-related)
View:xml, View, Activity, Fragment and other UI-related
ViewModel: That's what I'm talking about, and it's easy to understand that as a manager

Execution process

ViewModel is responsible for calling Model (which can be called a data source) and updating itself after getting the result. The view and the ViewModel are bound in two directions (which is how the bindings are implemented later), so the view is automatically updated.
This is the general idea of MVVM.

Environment configuration

First you need to introduce lifecycles, Livedata and ViewModel the three family barrels, and these libraries are placed on Google maven, so you have to add Google maven in the project root Gradle file

allprojects {
repositories {
Jcenter ()
Maven {URL ' https://maven.google.com '}
}
}
We then add the following 3 libraries to the Gradle file of the app module, in order to make it easier to modify the version number after the final release, by referencing the variable.

Lifecycles, Livedata and ViewModel
Compile "Android.arch.lifecycle:runtime: $rootProject. Lifecycleruntime"
Compile "android.arch.lifecycle:extensions: $rootProject. Lifecycle"
Annotationprocessor "Android.arch.lifecycle:compiler: $rootProject. Lifecycle"
Accordingly, you need to add additional attributes (Gradle syntax) to the root Gradle file.

ext {
Lifecycle = ' 1.0.0-rc1 '
Lifecycleruntime = ' 1.0.3 '
}
Model

To reduce the difficulty of learning, we intend to write a demo showing the user ID and name.
So the bean is really simply 2 properties, omitting the Get and set methods (which you add yourself when the reader exercises).

public class User implements Serializable {
private int id;
private String name;
... getter Setter and toString ...
}
The Model's finished, what? What about the data source?
Lie, don't panic! I'll talk about it next time.

View

So accordingly, we define 2 TextView to show the ID and name.

A_activity_user.xml

<?xml version= "1.0" encoding= "Utf-8"?>
<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "Http://schemas.android.com/tools"
android:orientation= "Vertical"
Android:id= "@+id/v_root"
br/>xmlns:app= "Http://schemas.android.com/apk/res-auto"
Xmlns:tools= "Http://schemas.android.com/tools"
android:orientation= "Vertical"
Android:id= "@+id/v_root"
Android:layout_width= "Match_parent"
android:layout_height= "Match_parent" >

 <TextView     android:id="@+id/tv_id"     android:gravity="center"     android:layout_width="match_parent"     android:layout_height="wrap_content" /> <TextView     android:id="@+id/tv_name"     android:gravity="center"     android:layout_width="match_parent"     android:layout_height="wrap_content" />

</LinearLayout>
It then initializes and obtains references in the Activity.
It is important to note that if your support Lib >= 26.0.0, it is good to inherit appcompatactivity directly. Otherwise, you need to inherit lifecycleactivity.

public class Useractivity extends Appcompatactivity {
Private TextView Tvid;
Private TextView Tvname;

 @Override protected void onCreate(@Nullable Bundle savedInstanceState) {     super.onCreate(savedInstanceState);     setContentView(R.layout.a_activity_user);     initView();     initData(); } private void initView() {     tvId = (TextView) findViewById(R.id.tv_id);     tvName = (TextView) findViewById(R.id.tv_name); } private void initData() {     // todo }

}
Lifecycle

The above mentioned lifecycleactivity, in fact there are lifecyclefragment, similar, in support Lib >= 26.0.0, the default Activity and Fragment base class inside has been integrated, do not need you to modify The You can see the official documents in detail Lifecycle

For managing the Activity/freagment lifecycle, it is easy to query the status of the current component life cycle. The corresponding relationship is as follows.

What the hell is that for?

As long as you hold Lifecycle, you know the life cycle of the container.
For example, once the lifecycleobserver is implemented, it can respond in a timely manner when the state changes. It is equivalent to having the model or others have a life cycle. (Do you still have this?) )

Define a location listener that can do the corresponding operation in different states of the life cycle, and no longer have to register or cancel the activity in addition to the life cycle.

Class Mylocationlistener implements Lifecycleobserver {
Private Boolean enabled = FALSE;
Public Mylocationlistener (context context, Lifecycle Lifecycle, Callback Callback) {
...
}

 @OnLifecycleEvent(Lifecycle.Event.ON_START) void start() {     if (enabled) {        // connect     } } public void enable() {     enabled = true;     if (lifecycle.getState().isAtLeast(STARTED)) {         // connect if not connected     } } @OnLifecycleEvent(Lifecycle.Event.ON_STOP) void stop() {     // disconnect if connected }

}
In Activity, you just need to pass in the lifecycle. The elegance is not good.

Mylocationlistener = new Mylocationlistener (this, getlifecycle (), location, {
Update UI
});
ViewModel

ViewModel is similar to the Presenter in MVP or the Controller in MVC. (It's not clear what an MVC MVP is, it's a concept.)

Now we have absolutely no need to define ViewModel to manage the UI life cycle, and there is a ViewModel in Google Pack

So it's natural for us to write a class like this.

public class Userviewmodel extends ViewModel {}
You may be curious about ViewModel, go inside and see that there is only an abstract class with an empty method. Yes, it's Google. But from oncleared this method name can be seen, this is still useful place.

Livedata

The next step is to call the Model and bind to the view, and before going on, we need to introduce livedata, yes, it can easily implement and view bindings.

It can automatically respond to life-cycle methods that can be observed (notifying observers when data changes), so the Model and View bindings can be implemented.

Has the following advantages:

Avoid memory leaks: Observer is automatically cleaned up when Lifecycle is destroyed due to Observer and Lifecycle bindings.
Avoid crashes: Prevent crashes caused by updating data after Activity is destroyed
Data can be shared: Data can be shared across multiple fragment. Global data sharing can even be achieved with single-instance Livedata
No need to process life cycle in Activity
Timely data Update: When the data is not visible in the UI updates, when visible, the data will be updated to the UI in time

Specific usage

Create a variable livedata, which is mutablelivedata.
And is returned by a method. Yes, it's so simple, just need new to come out of the line.

Create a livedata with a String
Private mutablelivedata<string> Mcurrentname;

Public mutablelivedata<string> Getcurrentname () {
if (Mcurrentname = = null) {
Mcurrentname = new mutablelivedata<string> ();
}
return mcurrentname;
}
Observe the Livedata in the activity/fragment. That is, when the livedata data changes, the automatic callback method to update the UI.

Final observer<string> nameobserver = new observer<string> () {br/> @Override

Update the UI, in this case, a TextView.
Mnametextview.settext (NewName);
}
};
Getcurrentname (). Observe (this, nameobserver);
When will the data be updated?

Updating data is usually triggered on this side of the UI, such as when we bind an event to a button and then click to change the name.

Mbutton.setonclicklistener (New Onclicklistener () {br/> @Override

String anothername = "John Doe";
Getcurrentname (). SetValue (Anothername);
}
});
Yes, you want to update the text on the UI, you just need to modify the data in the Livedata.

ViewModel + livedata

After Livedata, we went back to ViewModel.
In order to display the ID and name, we need a livedata.
A GetUser method and a Setusername method are disclosed externally.
Here you will find that GetUser is not thread-safe, because this case will not be getUser in multi-threading, so there is no need to add, in fact, you can also put the user initialization in the member variable definition place.

public class Userviewmodel extends ViewModel {
Private mutablelivedata<user> User;

 public LiveData<User> getUser() {     if (user == null)         user = new MutableLiveData<>();     return user; } public void setUsername(String username) {     user.setValue(new User(1, username)); }

}
View and ViewModel Bindings

Before mentioning the Livedata, it can be conveniently observed.
There are also ViewModel that can automatically respond to the life cycle.
So that's the two things that make it easy to implement a binding operation.

Before I had initialized the useractivity view, now to perfect the initdata.

Typically, a View is bound to only one ViewModel. So we need an Activity-level singleton ViewModel, which we can simply implement by Viewmodelproviders.of (this). Get (Userviewmodel.class).

The Livedata is then acquired through Userviewmodel and a listener (bind operation) is added.

Within this callback method, we can update the UI associated with that data.

Yes, binding is so simple and convenient.

Private Userviewmodel Userviewmodel;

private void InitData () {
Userviewmodel = Viewmodelproviders.of (this). get (Userviewmodel.class);
Userviewmodel.getuser (). Observe (this, new observer<user> () {br/> @Override

Updateview (user);
}
});

 userViewModel.setUsername("ittianyu");

}

private void Updateview (user user) {
Tvid.settext (User.getid () + "");
Tvname.settext (User.getname ());
}
Summarize

With such a framework, it is not necessary to have a headache for the complex UI logic that is caused by the View being modified at N.

Data requests can also be more purely, without the need for a tube UI to be displayed.

In a nutshell, after the request data is complete and the data is updated, the interface is rendered according to the data by notifying the UI.

Yes, Android can also write the UI as happily as the front end. It is also possible to concentrate on the data as well as the back end.

The application of the Android-in-the-text MVVM tutorial

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.