Take you into the world of MVP +dagger2 + databinding+ Rxjava+retrofit

Source: Internet
Author: User
Tags throwable

0.0 Android Development now changes in a word to describe is: shaking

More and more projects are using MVP + Rxjava+retrofit +dagger2 + databinding and so on. But these things for the wood useful students to open up still more headache.
Reprint please indicate source: http://blog.csdn.net/wingichoy/article/details/51981756
There are many tutorials on the web that introduce them, but they are more detailed (I heard the children's shoes asked: details are not good?? In fact, their best way to learn is to tap the side of the pit to learn, the introduction of too detailed, for beginners can only have the effect of Meng , so prepare to write a relatively simple blog, to introduce the simple use of these things. Everyone to follow the knock, even beginners should not be very ignorant force.

Before we start, let's talk about the effects of these things.

1.MVP Everyone knows that P's role is to let the MV indirectly have dirty py deals, rather than letting them trade directly.
2.Rxjava Responsive programming 0.0 a special cock is where you can switch threads.
3.Retrofit instead of volley
4.dagger2 Android's IOC framework, i.e. control inversion, also called dependency injection
4.DataBinding MVVM, it is more convenient to use, you can let the bean and view binding, Discard SetText ()!

More things, but suppress fear! One of us to understand their simplest usage.

Tell you a secret, actually.

Mvp

The

MVP has a brief introduction to http://blog.csdn.net/wingichoy/article/details/50893367, and the new drivers can take a look at them first.
The previous MVP has to define 3 interfaces IModel IView IPresenter respectively. Write more, you will find that tete occupy the place ... A workaround here is to refer to a contract class. Plainly, three interfaces are put together.

public  interface  maincontract  { / /view interface  interface   MainView  { void  showData (Apibean.retdatabean retdatabean); void  Showprogressbar (); } //presenter interface  interface  mainpresenter  { void  getmaindata ( ); } //model interface  interface  mainmodel  { Observable loadmaindata (); }}

In the MVP, M is responsible for the business logic (IO operation) v is the activity, responsible for interacting with the user, p is the bridge between the two of them. Like the Cowboy (M) Weaver (V), the Cowherd to meet with the weaver, must have a bridge (P) Ah.

Dagger2

Dagger is a dependency injection, decoupling. A common place to use is to inject presenter into the activity.

Examples are as follows

public   Class  mainactivity  extends  appcompatactivity  implements   Maincontract . mainview  { Maincontract.mainpresenter mpresenter;  @Override  protected  void  oncreate  (Bundle savedinstancestate) {super . OnCreate (savedinstancestate); //mpresenter no longer creates  Mpresenter = Daggermaincomponent.builder () in new form. Mainmodule ( Span class= "Hljs-keyword" >new mainmodule (this ). Build (). Getpresenter (); 

What is the benefit of doing this, for example, now that the presenter need a parameter to construct, to the back of the need to change, need two, if you use new. As long as the modification presenter also have to modify activity,0.0 coupling degree too! High! The If this is the way, you can happily modify the presenter, no matter how the presenter changes, the activity code does not need to change.

Methods for using Dagger2 1. configuring

In the app's Gradle, add:

    "com.google.dagger:dagger:2.4"    "com.google.dagger:dagger-compiler:2.4"    ‘org.glassfish:javax.annotation:10.0-b28‘

Top of the Join

‘com.neenbedankt.android-apt‘

Join the Gradle in Project

‘com.neenbedankt.gradle.plugins:android-apt:1.8‘
2. Use

Or just for example, we want to inject presenter, and then add annotations to the presenter constructor for a long time @inject

publicclass MainPresenterImpl implements MainContract.MainPresenter {    private MainContract.MainView mMainView;    private MainContract.MainModel mMainModel;    @Inject    publicMainPresenterImpl(MainContract.MainView mainView) {        mMainView = mainView;        new MainModelImpl();    }

A module is then built to provide dependencies (parameters required by the presenter constructor)

@Modulepublicclass MainModule {    private MainContract.MainView mMainView;    //Module的构造器,传入一个MainView, 提供给Component    publicMainModule(MainContract.MainView mMainView) {        this.mMainView = mMainView;    }    //Provides注解代表提供的参数,为构造器传进来的    @Provides    publicinject(){        return mMainView;    };}

Then build a component, note the above annotations, and represent the use of Mainmodule

@Component(modules = MainModule.class)publicinterface MainComponent {    MainPresenterImpl getPresenter();}

And finally inject the activity into the operation.

mPresenter = DaggerMainComponent.builder().mainModule(new MainModule(this)).build().getPresenter();

The straight note is that the component at the beginning of the dagger is created during the build process, and if you write for the first time, rebuild first. This completes the injection of presenter. See here you may have been confused, it doesn't matter, according to more knock several times, as the saying goes, code times, its righteousness from now. The fact is that using component to create a presenter, and presenter the required parameters are provided by Moudule.

DataBinding1. Configuration

Add in the app's Gradle

    compile "com.jakewharton.rxbinding:rxbinding:0.4.0"    compile "com.jakewharton.rxbinding:rxbinding-design:0.4.0"

Add in andrid{}

    24    "24.0.0"    dataBinding {        true    }}
2. How to use

The first thing to change is the layout file, layout with layout

<layout xmlns:android="http://schemas.android.com/apk/res/android"xmlns: Tools="Http://schemas.android.com/tools"tools:context=". View.activity.MainActivity" >            <relativelayoutandroid:layout_width="Match_parent"android:layout_height ="Match_parent">                            <TextViewandroid:id="@+id/tv_test"android:layout_width="Wrap _content "android:layout_height=" Wrap_content "android:text=" @{ Phone.phone} " />                                                                    </relativelayout>

The

Then replaces the Setcontentview () of the system itself in the code, and then the layout object can be manipulated.

public   class  mainactivity  extends  appcompatactivity  implements  maincontract . mainview     { private  activitymainbinding mbinding;     @Override  protected  void  oncreate  (Bundle savedinstancestate)        {super . OnCreate (savedinstancestate);        mbinding = Databindingutil.setcontentview (this , R.layout.activity_main);    MBinding.tvTest.setText ( "hello" ); }
3. Bind the Data

There is more data under the Layout tab to define the introduction class. For example, there is an entity Retdatabean, which stores the phone and other information, you can directly display the entity information on the view.

    <data>        <variablename= "phone"type=" Com.wingsofts.rxretrofitmvpdagger2databinding.bean.ApiBean.RetDataBean " />                           </Data>    <relativelayoutandroid:layout_width="Match_parent"android:layout _height="Match_parent">                            <TextViewandroid:id= "@+id/tv_test"android:layout_width="Wrap_ Content "android:layout_height=" Wrap_content "android:text="@{phone.phone} " />                                                                    </relativelayout>

The above represents the definition of a Retdatabean class variable, named Phone, to refer to him in Android:text.
and add the data to the activity.

  @Override    publicvoidshowData(ApiBean.RetDataBean retDataBean) {        mBinding.setPhone(retDataBean);    }

This is the simple use of databinding.

RXJAVA1. Configuration

Add the following code to the app's Gradle

    compile "io.reactivex:rxandroid:1.2.0"    compile "io.reactivex:rxjava:1.1.7"
2. Use

Simply say the basic syntax. In fact Rx is the dirty py trade between observable and subscriber. Children's shoes that do not recognize these two words can be knocked 100 times before the face is ripe. Don't be afraid, just. Observable is the source of the event, Subscriber is the Subscriber, when the event source occurs time, subscriber make corresponding response, you can take to compare with Onclicklistener. Look at a simple chestnut:

Sampleobservalbe.subscribe (NewSubscriber<apibean> () {@Override                     Public void oncompleted() {//When all OnNext () have been executed and punished}@Override                     Public void OnError(Throwable e) {//When the error is triggered}@Override                     Public void OnNext(Apibean Apibean) {//Trigger when sampleobservable event occursLOG.E ("Wing","OnNext"); }                });

The above code is a simple Rxjava using syntax. When the Sampleobservable event occurs, call the new Subscriber OnNext method. At this point you may have doubts, this sampleobservable where to come, of course, the keyboard knocked out! In conjunction with retrofit, retrofit API will return a observable to you, of course, network access can no longer mainthread, don't ask me why. Then the strength of the Rxjava is reflected, you can switch threads at will! For example, we get retrofit return observable, want him to access the network in the worker thread, call Subscribeon directly (Schedulers.io ()), when the data returned to subscriber, only need to call
Observeon (Androidschedulers.mainthread ()) can, completely abandoned what handler there is wood!!! Dick not dick!! So the code described above is as follows:

Mmainmodel.loadmaindata (). Observeon (Androidschedulers.mainthread ())//When the data is received in the main thread. Subscribeon (Schedulers.io ())//Access data on worker threads. Subscribe (NewSubscriber<apibean> () {@Override                     Public void oncompleted() {                    }@Override                     Public void OnError(Throwable e) {                    }@Override                     Public void OnNext(Apibean Apibean)                        {Mmainview.showdata (Apibean.getretdata ()); LOG.E ("Wing","OnNext"); }                });

The simple usage of Rxjava is introduced here, because the main purpose of this article is to let the reader personally easily knocked up, in the process of tapping the code to step on the pit, in the process of growing. If need to know more, recommend: Throw the line of the great God this article

Retrofit1. Configuration

Add the following code to the app's Gradle

    "com.squareup.retrofit2:retrofit:2.1.0"    "com.squareup.retrofit2:converter-gson:2.1.0"    "com.squareup.retrofit2:adapter-rxjava:2.1.0"    "com.squareup.okhttp3:3.4.1"    "com.squareup.okhttp3:logging-interceptor:3.4.1"    ‘com.google.code.gson:gson:2.4‘
2. Use

As I said earlier, retrofit can return a observable object based on the interface and see how to use it.
For example, the interface I want to access is: http://wifikey.org/api/api.php
First, generate a bean with Gsonformat,
Then define the following interface

    publicinterface DataApi {    @GET("api.php")Observable<ApiBean> getData();}

Using retrofit to generate retrofit objects in code

//Constant.HOST =http://wifikey.org/api/ mApi = new Retrofit.Builder().baseUrl(Constant.HOST).addConverterFactory(GsonConverterFactory.create())                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())                .build().create(DataApi.class);

At this point Dataapi is created successfully, call Dataapi's GetData () method, will return a observable object, then what to do, you know it.

Here, the MVP +dagger2 + databinding+ Rxjava+retrofit's brief introduction is complete. Hope that we have a lot of hands knocking, knock, after the online there are many excellent individual introduction of the article, and strive to trample the pit, in order to grow. If you like my blog, you can follow me, comment on me, not too much, crab crab!

Click to download the project

Take you into the world of MVP +dagger2 + databinding+ Rxjava+retrofit

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.