Android Official MVVM Framework implements the overall structure of the component

Source: Internet
Author: User

First, Google's official MVVM framework Explained

I contrasted the MVC and MVP "two charts to understand the difference between MVC and MVP in Android development", which is how superior we are to MVC, but Android development is now popular with MVVM, and Google officially released the official MVVM library shortly before. Officially, the official MVVM library consists of the following four main posts:

Only ViewModel is a component in the MVVM structure, and the other three are of an auxiliary nature.

Lifecycles is the life cycle of the UI interface, and in the support library after version 26, Lifecycleowner is implemented in both Appcompatactivity and supportactivity. The UI interface has been processed internally for the life cycle.

Livedata is an abstract class, we can store the data that the UI page needs, is to wrap the data in the livedata, we can observe the data changes in Livedata, but Livedata is associated with the UI life cycle, when the UI page is destroyed, The Livedata data change callback is not executed.

The hostel is a SQLite data persistence library, and we can use other ORM libraries as well.

Second, the MVVM architecture Advantage

"Two pictures to understand the difference between MVC and MVP in Android development" front two pictures It's the difference between MVC and MVP, and here's a picture to look at MVVM:

There is no relationship between model and view, ViewModel is the processing plant that associates the view with the model:

MVVM Advantage Summary:

1,view and model two-way binding, one side of the change will affect the other side, the developer no longer have to manually modify the UI data. Well, it's automatic with each other.

2, do not need Findviewbyid also do not need to butterknife, do not need to get the specific view to set the data binding listener, and so on, these can be completed with databinding. Isn't it comfortable?

The two-way binding of the 3,view and model is to support lifecycle detection, without worrying about the page being destroyed and the callback happening, which is done by lifecycle.

4, will not be like MVC as the code volume in the activity is huge, and will not be like the MVP of a large number of view and presenter interface. The project structure is less coupled.

5, the lower coupling of the various modules developed separately, separate testing, can be divided into different developers to complete.

Iii. MVVM Component Example Project architecture analysis

is the dependency between the Project module and the project:

Is the directory structure in engineering Android Studio:

3.1 Explanation of the relationship between the modules and each other:

Lib_opensource: Third party Build.gradle relies on, this project mainly has support, lifecycle, the hostel, fresco, retrofit, Okhttp, RxJava, Arouter these.

Libcoremodel: Storing the model and ViewModel two modules in MVVM is the processing of data and the binding of data to the UI page. Rely on the Libopensource library.

Libcommon: Public libraries, mainly have various base, various UI components, custom components, common activity, common fragment, and common utils, etc. Rely on the Libcoremodel library.

Module_girls: Sister function module, you can switch between the library and application, you can be an app can also become a component module of other apps. The component is compiled for the app, and vice versa for module.

Module_news: News function module, you can switch between the library and application, you can be an app can also become a component module of other apps. The component is compiled for the app, and vice versa for module.

Appuniversal: Custom version of the app, component compile-time modulegirls and Modulenews as the app, so the two can not be added as a module to compile, so the component compile-time appuniversal to rely on the Libcommon library , you can add Modulegirls and Module_news as a module in the compilation.

AppSpecific: Custom version of the app, component compile-time modulegirls and Modulenews as the app, so you can't add these two as a module to compile, so the component compile-time appspecific to rely on the Libcommon library, Instead, you can add Modulegirls and Module_news as a module in the compilation.

3.2 Arouter series of various modules

Use Arouter to jump activity and get fragment, remember to look at other people's component structure of the article, has been tangled in the fragment of the acquisition problem, I would like to say that there is arouter to get fragment is not super simple?

Arouter Typical applications

Mapping from external URLs to internal pages, and parameter passing and parsing
Cross-module page jumps, decoupling between modules
Intercept the jump process, deal with the logic of landing, burying point, etc.
Cross-module API calls to decouple components by controlling inverse
3.3 Component compilation and non-component compilation switching

We add a Boolean variable to the Gradle.properties file in the project root directory to identify the compilation mode by modifying this variable:

Each time you change the value of "IsModule", you need to click the "Sync Project" button ismodule is the "Integrated development Mode" and "Component development mode" toggle switch

Ismodule=false
The switch is then supported in the Build.gradle file in Modulegirls and modulenews:

if (Ismodule.toboolean ()) {
Application at component compile time
Apply plugin: ' Com.android.application '
} else {
Non-component compile time for library
Apply plugin: ' Com.android.library '
}

Android {
Compilesdkversion BUILD_VERSIONS.TARGET_SDK
Buildtoolsversion Build_versions.build_tools

defaultconfig {minsdkversion build_versions.min_sdk targetsdkversion build_versions.target_sdk versionCode 1 Versionname "1.0" Testinstrumentationrunner "Android.support.test.runner.AndroidJUnitRunner"//arouter Javacompil eoptions {annotationprocessoroptions {arguments = [ModuleName:project.getName ()]}}}buildt Ypes {release {minifyenabled false proguardfiles getdefaultproguardfile (' proguard-android.txt '), ' Progu Ard-rules.pro '}}databinding {enabled = true}lintoptions {abortonerror False}sourcesets {main {if ( Ismodule.toboolean ()) {//component compiled at compile time for app, in corresponding androidmanifest file requires write Ndroid.intent.action.MAIN entry activity ma Nifest.srcfile ' Src/main/module/androidmanifest.xml '} else {manifest.srcfile ' src/main/androidmanifest                . xml '//integrated development mode excludes all Java files in the Debug folder the Java {//debug folder is placed in the application class, which is not required for non-assembly Exclude ' Debug/** '}}}} 

}

dependencies {
Implementation Filetree (dir: ' Libs ', include: [' *.jar '])
API Project (': Lib_coremodel ')
API Project (': Lib_common ')
Implementation ' com.android.support:support-v4:26.1.0 '
Annotationprocessor Deps.arouter.compiler
}
As seen above, the component and non-component compilation will have no Androidmanifest file, when the component requires the Debug folder under the Application class, non-component exclusion of this folder.

The Androidmanifest file under module is compiled by the component app and writes the main entry activity

Dubug is the application class when the component app compiles, initializing the resources needed to run as an app, and so on. In the non-assembly compilation in the Build.gradle file excludes the Debug folder so something.

3.4 Final Notice:

There are a few columns later that describe using Arouter during the MVVM component to jump activity and get fragment, databinding implement data and UI bindings, RXJAVA2, and Retrofit2 Dynamic Data acquisition. and the Androidviewmodel package.

The following is a Lib_coremodel library in my encapsulated Androidviewmodel, with generics to determine the data type, and is a dynamic URL to get the data:

Package Google.architecture.coremodel.viewmodel;

Import android.app.Application;
Import Android.arch.lifecycle.AndroidViewModel;
Import Android.arch.lifecycle.LiveData;
Import Android.arch.lifecycle.MutableLiveData;
Import Android.databinding.ObservableField;
Import Android.support.annotation.NonNull;

Import java.io.IOException;
Import Java.lang.reflect.ParameterizedType;

Import google.architecture.coremodel.datamodel.http.ApiClient;
Import google.architecture.coremodel.datamodel.http.ApiConstants;
Import Google.architecture.coremodel.datamodel.http.service.DynamicApiService;
Import Google.architecture.coremodel.util.JsonUtil;
Import Io.reactivex.Observer;
Import Io.reactivex.android.schedulers.AndroidSchedulers;
Import io.reactivex.disposables.CompositeDisposable;
Import io.reactivex.disposables.Disposable;
Import Io.reactivex.schedulers.Schedulers;
Import OKHTTP3. Responsebody;

/**

    • Created by dxx on 2017/11/20.
      */

public class Baseviewmodel<t> extends Androidviewmodel {

Data for life cycle observations private mutablelivedata<t> Liveobservabledata = new mutablelivedata<> ();//ui Use observable data Observablefield is a wrapper class public observablefield<t> Uiobservabledata = new observablefield<> ();p rivate final Compositedisposable mdisposable = new compositedisposable ();p rivate static final Mutablelivedata ABSENT = new mutablelive Data (); {//noinspection unchecked absent.setvalue (null);}    Public Baseviewmodel (@NonNull application application, String FullUrl) {super (application); Apiclient.initservice (Apiconstants.gankhost, Dynamicapiservice.class). Getdynamicdata (FULLURL). SubscribeOn (        Schedulers.io ()). Observeon (Androidschedulers.mainthread ()). Subscribe (New observer<responsebody> () {        @Override public void Onsubscribe (disposable d) {mdisposable.add (d);                   } @Override public void OnNext (responsebody value) {if (null! = value) {try { Liveobservabledata.setvalue (JsonUtil.str2jsonbean (Value.string (), Gettclass ()));               } catch (IOException e) {e.printstacktrace (); }}} @Override public void OnError (Throwable e) {} @Override Public void OnComplete () {}}); /** * Livedata supports lifecycle life cycle detection * @return */public livedata<t> getliveobservabledata () {return Liveobservableda Ta;} /** * Re-set the observed data when actively changing data * @param product */public void Setuiobservabledata (T product) {This.uiObservableData.set (prod UCT);} Public class<t> Gettclass () {class<t> Tclass = (class<t>) ((Parameterizedtype) getclass ().    Getgenericsuperclass ()). Getactualtypearguments () [0]; return tclass;}    @Overrideprotected void oncleared () {super.oncleared (); Mdisposable.clear ();}

}

Android Official MVVM Framework implements the overall structure of the component

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.