When Dagger2 is used in the MVP framework

Source: Internet
Author: User

Original link: When Dagger2 is used in the MVP framework

About Dagger2 oneself a want to understand, but from last year to now, said really, read a lot of introduction Dagger2 article, but own a foggy, recently intends to apply DAGGER2 to the MVP framework, so on re-read the relevant technical articles, re-study, Below is oneself these two days study Dagger2 after the understanding of Dagger2, not necessarily all correct, if wrong, welcome correct, as long as from the code point of view, know Dagger2.

Note: If you are unfamiliar with MVP and Retrofit, this article may not be suitable for you to read.

Learning Intentions

The previous period in accordance with the MVP framework to reconstruct a sister client gankdaily, about the MVP in the gankdaily How to use, I also wrote an article introduced, MVP mode in gankdaily application, if you have seen gankdaily code, its It is not just gankdaily this project, all projects that use the MVP architecture, there is a problem, that is, each Activity must have a Presenter instance object, as shown below

/**  * the presenter of this Activity  */private MainActivityPresenter mPresenter;

It is the Activity controller, all data requests, interface updates are directly or indirectly controlled by it. Then each activity needs to instantiate it in OnCreate, as shown below

new MainActivityPresenter(this, user);

There's nothing wrong with that, but if you've ever heard of dependency injection (a good thing about dependency injection, a buddy writing article, a Dependency injection principle), there's a lot of downside to using the New keyword to instantiate an object, and the new instance is actually hard-coded. Why?

Imagine that, if the parameters in the Mainactivitypresenter constructor change in the future, then, not only in the Mainactivitypresenter class changed the Mainactivitypresenter constructor-related code, You also need to change the code in all the places where you use Mainactivitypresenter, isn't it hard-coded?

Are you sure you want to ask? "Do you have any other way to avoid this kind of problem?" you said.

The answer is today's theme –dagger2

Imagine, if the Mainactivitypresenter instance of the acquisition, in advance through an auxiliary class contract, then the specific use, through the auxiliary class to generate Mainactivitypresenter object, then is not better, in fact, this auxiliary class, What I understand here is the Module concept in Dagger2.

Of course Dagger2 can solve the problem of hard coding, there are many other advantages, such as convenient testing and so on.

The above is the original intention of learning, summed up, I use Dagger2 's vision or the final expected result is not in the activity see new Presenter () such code, directly in the definition of Presenter instance, with @Inject annotation, Pres The instance of enter is generated.

Final result

Below you will use DAGGER2 + MVP architecture mode + Retrofit to demonstrate a simple demo.

This demo has only one mainactivity interface, and the final effect is to get a string displayed in Mainactivity via Mainactivitypresenter in Mainactivity.

Here about Dagger2 and MVP you should already understand why they exist, but for Retrofit may be a little puzzled about Retrofit:

Retrofit: Used to simulate the general network data acquisition, which is now used more, but also is a very convenient library, plus support RxJava, it is very convenient for data acquisition. Now that you want to use Retrofit, you should know that there is only one Retrofit instance that is best used throughout the application.

Environment configuration

The root directory of the build file joins ANDROID-APT support

sub-projects/modules.buildscript {    repositories {        jcenter()    }    dependencies {        ‘com.android.tools.build:gradle:1.1.0‘        ‘com.neenbedankt.gradle.plugins:android-apt:1.4‘        not place your application dependencies here; they belong        // in the individual module build.gradle files    }}

Add the support for apt plugin in the app directory build file

‘com.neenbedankt.android-apt‘

Join Dagger2 Retrofit OkHttp Dependency

//dagger2‘com.google.dagger:dagger:2.0‘‘com.google.dagger:dagger-compiler:2.0‘‘org.glassfish:javax.annotation:10.0-b28‘//Square‘com.jakewharton:butterknife:6.1.0‘‘com.squareup.retrofit:retrofit:1.9.0‘‘com.squareup.okhttp:okhttp:2.3.0‘
Practice Dagger2 in Application

Now that the dependencies have been added, start using Dagger2, the first step is to consider our application.

Create appapplication first, and register well in Androidmainfest.xml.

public   class  appapplication  extends  application  {  @Override  public  void  oncreate  () {super.oncreate (); }}
<application       android:name=".AppApplication"       android:allowBackup="true"       android:icon="@mipmap/ic_launcher"       android:label="@string/app_name"       android:theme="@style/AppTheme" ></application>

Think about it here, what should we do in application? Application in general can do a number of global related things.

For Retrofit, the front also said that there should be only one instance in the global, so application can have a global Retrofit.

Speaking here, feel a little hard, the main thing is not enough to understand the depth, first of all, it is written to their own later to see, if you, are reading the article you caused confusion, but also forgive me. If reading the article is a bit laborious, it is recommended to look directly at the final source code that already exists on GitHub

Based on the above analysis, application may need a dependency, depending on apiservicemodule (providing Retrofit instance), here we look at the Apiservicemodule code implementation

@Module Public  class apiservicemodule {    Private Static FinalString endpoint="";@Provides    @SingletonOkhttpclient provideokhttpclient () {Okhttpclient okhttpclient =NewOkhttpclient (); Okhttpclient.setconnecttimeout ( -* +, timeunit.milliseconds); Okhttpclient.setreadtimeout ( -* +, timeunit.milliseconds);returnOkhttpclient; }@Provides    @SingletonRestadapter providerestadapter (Application application, Okhttpclient okhttpclient) {RestAdapter.Builder Builder =NewRestadapter.builder (); Builder.setclient (NewOkclient (Okhttpclient)). setEndPoint (ENDPOINT);returnBuilder.build (); }@Provides    @SingletonApiservice Provideapiservice (Restadapter restadapter) {returnRestadapter.create (Apiservice.class); }}

The beginning of any Module class is annotated with @Module.

Then, the final apiservicemodule needs to be provided to the appapplication, here can not directly apiservicemodule to appapplication, now need a component to integrate him this component we named him Appco Mponent below is the implementation of it.

@Singleton// 如果这里有多个 可以用逗号隔开,继续追加@Component(modules = {ApiServiceModule.class})publicinterface AppComponent {    ApiService getService();}

Here you will see that he is an interface, and then at the beginning of the class declaration, with @Component specified his specific dependent class.

This interface has only one method, which returns a global instance Apiservice that was previously conceived.

Since it is an interface, then there must be a class to implement him, imagine, if there is a class to implement the above interface, we just have to get the object of this implementation in Appapplication, then this object is not AppComponent, then we do not pass AppComponent Did you get to the instance object? Well, that should be it.

Now that the AppComponent interface is defined and compiled, you will automatically be prompted to daggerappcomponent this class when you play the Dagger editor in the editor.

Well? What's going on?

This is actually Dagger2 help you to generate automatically.

Now in appapplication directly use daggerappcomponent, use it to get AppComponent object, and then have AppComponent then Apiservice not come with it?

The code in Appapplication now looks like this

 Public  class appapplicationextends application{       Public StaticAppapplicationGet(Context context) {return(appapplication) Context.getapplicationcontext (); }PrivateAppComponent AppComponent;@Override     Public void onCreate() {Super. OnCreate (); Appcomponent=daggerappcomponent.builder (). Apiservicemodule (NewApiservicemodule ()). build (); } PublicAppComponentgetappcomponent() {returnAppComponent; }}

So now as long as you want to get an instance of Apiservice anywhere, as long as you get an instance of Appapplication (Appapplication.get (), you can pass Appapplication getappcomponent () The method obtains the AppComponent, then can obtain the Apiservice instance indirectly through the AppComponent.

Above probably said under the application in the application of Dagger2 to instantiate AppComponent, in fact, the use of Activity is the same truth. Now there is no time to write about how to use Dagger2 in Activity, which can be viewed from the code.

Code is already on Github, welcome to

When Dagger2 is used in the MVP framework

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.