Dagger2在MVP中的应用

Dagger2在MVP中的应用

转载说明出处:http://blog.csdn.net/a15286856575/article/details/53405630

需要基础

建议把基础学会再看下面文章好理解点。

为什么MVP中要用Dagger2?

我们首先看一下传统的mvp有什么缺点?

  • presenter在Activity的耦合

    我们知道在传统的MVP中Preseter是在Activity中初始化的,也就是显式的new了一个对象,那么这里面在这个Activity中就有了耦合在里面。为什么会有耦合呢?

    • 场景1: 假如你的项目中多次用到了这个Presetner,现在有这么个需求,这个Presenter依赖某个对象,需要在构造方法中传入这个对象,我们是不是要找到所有找到所有初始化这个Presenter的对象,然后去修改它,小项目还可以如果是大项目,我们是不是要找到所有的去修改。这就产生了耦合。怎么解决?Daggger2是个依赖注入框架,当前的Activity不用关心Presenter,是怎么创建的,具体的创建交给module.我们只需要修改module. .
    • 场景2:假如Presenter需要对象A,对象A需要对象B,对象B需要对象C,我们是不是先C c= new B(),B b = new B(c),A a = new A(B) 然后在初始化Presenter。像这种情况,我们是不是每次都需要这样写,在Activity中还要关系他们的创建顺序。很繁琐,用Dagger2就可以解决这个问题。我们通过依赖注入,注入我们需要的对象,就大功告成了。
  • model在Presenter中的耦合

    传统的的mvp中的model是在Presenter中进行初始化的,这里面也是显示的new了一个对象。同样也会有一个耦合在里面。

    • 场景1:多个Presenter用了同一个model类,有同样的需求,model需要传入一个对象,我们是不是要找到用了这个model的所有Presenter,一个一个修改。里面是不是有耦合。同样我们可以通过dagger2注入model,在dagger2的module修改这个model就行了。
    • 场景2:初始化一个Model,需要对象A,对象A需要对象B,对象B需要对象C,我们是不是先C c= new B(),B b = new B(c),A a = new A(B),然后初始化Model。我们在对model进行重用的时候,每次都要这样做很繁琐,通过dagger2中提供的创建的Module,我们可以注入这个model,是不是很省事。

注意module是Dagger2中的,model是mvp中的
当然Dagger2不仅仅局限于MVP,在有耦合的地方都可以用。


Dagger2在MVP中的具体实现

架构思路:对于上面两种情况。他们可以有同一个Module提供,那我们就可以有一套依赖体系实现,例如登录,我们LoginModule提供Presenter和Model,LoginComponent负责注入,就行了。但是我们还需要一个全局的AppModule,提供OkHttpClient ,Sevivce,Retofit。然后让LoginComponent依赖他就行了。那么我们在LoginComponent,就能够拿到所有的Module.如图:


image

我们需要两个Component:

AppComponent

AppCompponet是在Applcation中初始化的所有是个全局的Component代码如下

@Singleton
@Component(modules = {AppModule.class, ClientModule.class, ServiceModule.class})
public interface AppComponent {

    Application Application();
    
    ApiService  apiService();
}


这个组件相当于工厂管理员,他管理着AppModule,ClentModule,ServiceModule
通过他我们能找到这些Module所提供的实例。如果在其他Component依赖此Component,我们有需要那些module所提供的实例,那么我们就需要在AppComponent暴露这些对象,在这里我们暴露了Application ApiService;

  • AppModule 主要提供Application对象。
@Module
public class AppModule {
    private Application mApplication;

    public AppModule(Application application) {
        this.mApplication = application;
    }

    @Singleton
    @Provides
    public Application provideApplication() {
        return mApplication;
    }

    @Singleton
    @Provides
    public Gson provideGson(){return new Gson();}
}
  • ClientModule 主要提供Retofit对象.其中包括了配置我们需要的Retofit
@Module
public class ClientModule {
    private static final int TOME_OUT = 10;
    public static final int HTTP_RESPONSE_DISK_CACHE_MAX_SIZE = 10 * 1024 *     1024;//缓存文件最大值为10Mb
    private HttpUrl mApiUrl;
    private GlobeHttpHandler mHandler;
    private Interceptor[] mInterceptors;
    /**
     * @author: jess
     * @date 8/5/16 11:03 AM
     * @description: 设置baseurl
     */
    private ClientModule(Buidler buidler) {
        this.mApiUrl = buidler.apiUrl;
        this.mHandler = buidler.handler;
        this.mInterceptors = buidler.interceptors;

    }

    public static Buidler buidler() {
        return new Buidler();
    }

    /**
     * @param cache     缓存
     * @param intercept 拦截器
     * @return
     * @author: jess
     * @date 8/30/16 1:12 PM
     * @description:提供OkhttpClient
     */
    @Singleton
    @Provides
    OkHttpClient provideClient(Cache cache, Interceptor intercept) {
        final OkHttpClient.Builder okHttpClient = new OkHttpClient.Builder();
        return configureClient(okHttpClient, cache, intercept);
    }

    /**
     * @param client
     * @param httpUrl
     * @return
     * @author: jess
     * @date 8/30/16 1:13 PM
     * @description: 提供retrofit
     */
    @Singleton
    @Provides
    Retrofit provideRetrofit(OkHttpClient client, HttpUrl httpUrl) {
        final Retrofit.Builder builder = new Retrofit.Builder();
        return configureRetrofit(builder, client, httpUrl);
    }

    @Singleton
    @Provides
    HttpUrl provideBaseUrl() {
        return mApiUrl;
    }
    /**
     * @param builder
     * @param client
     * @param httpUrl
     * @return
     * @author: jess
     * @date 8/30/16 1:15 PM
     * @description:配置retrofit
     */
    private Retrofit configureRetrofit(Retrofit.Builder builder, OkHttpClient client, HttpUrl httpUrl) {
        return builder
                .baseUrl(httpUrl)//域名
                .client(client)//设置okhttp
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())//使用rxjava
                .addConverterFactory(GsonConverterFactory.create())//使用Gson
                .build();
    }

    @Singleton
    @Provides
    Cache provideCache(File cacheFile) {
        return new Cache(cacheFile, HTTP_RESPONSE_DISK_CACHE_MAX_SIZE);//设置缓存路径和大小
    }
    /**
     * 提供缓存地址
     */
    @Singleton
    @Provides
    File provideCacheFile(Application application) {
        return DataHelper.getCacheFile(application);
    }

    @Singleton
    @Provides
    Interceptor provideIntercept() {
        return new RequestIntercept(mHandler);//打印请求信息的拦截器
    }

    /**
     * 配置okhttpclient
     *
     * @param okHttpClient
     * @return
     */
    private OkHttpClient configureClient(OkHttpClient.Builder okHttpClient, Cache cache, Interceptor intercept) {
        OkHttpClient.Builder builder = okHttpClient
                .connectTimeout(TOME_OUT, TimeUnit.SECONDS)
                .readTimeout(TOME_OUT, TimeUnit.SECONDS)
                .cache(cache)//设置缓存
                .addNetworkInterceptor(intercept);
        if (mInterceptors != null && mInterceptors.length > 0) {//如果外部提供了interceptor的数组则遍历添加
            for (Interceptor interceptor : mInterceptors) {
                builder.addInterceptor(interceptor);
            }
        }
        return builder
                .build();
    }
    public static final class Buidler {
        private HttpUrl apiUrl = HttpUrl.parse("https://api.github.com/");
        private GlobeHttpHandler handler;
        private Interceptor[] interceptors;

        private Buidler() {
        }

        public Buidler baseurl(String baseurl) {//基础url
            if (TextUtils.isEmpty(baseurl)) {
                throw new IllegalArgumentException("baseurl can not be empty");
            }
            this.apiUrl = HttpUrl.parse(baseurl);
            return this;
        }

        public Buidler globeHttpHandler(GlobeHttpHandler handler) {//用来处理http响应结果
            this.handler = handler;
            return this;
        }

        public Buidler interceptors(Interceptor[] interceptors) {//动态添加任意个interceptor
            this.interceptors = interceptors;
            return this;
        }

        public ClientModule build() {
            if (apiUrl == null) {
                throw new IllegalStateException("baseurl is required");
            }
            return new ClientModule(this);
        }
    }
}

在ClientModule中我们找到了一个加了@providers注解返为Retofit的方法

 @Singleton
    @Provides
    Retrofit provideRetrofit(OkHttpClient client, HttpUrl httpUrl) {
        final Retrofit.Builder builder = new Retrofit.Builder();
        return configureRetrofit(builder, client, httpUrl);
    }

里面需要传入OkHttpClient,HttpUrl对象。他们是怎么初始化的呢。在当前的ClientModule我们又发现了

  @Singleton
    @Provides
    OkHttpClient provideClient(Cache cache, Interceptor intercept) {
        final OkHttpClient.Builder okHttpClient = new OkHttpClient.Builder();
        return configureClient(okHttpClient, cache, intercept);
    }
@Singleton
    @Provides
    HttpUrl provideBaseUrl() {
        return mApiUrl;
    }

里面待参数的依次查找完成初始化工作,这里就不写了

  • ServiceModule 主要是提供ApiSevice对象
@Module
public class ServiceModule {

    @Singleton
    @Provides
    ApiService provideCommonService(Retrofit retrofit) {
        return retrofit.create(ApiService.class);
    }
}

ApiService初始化需要一个Retofit,这个Retrofit是有

  • AppComponent初始化

既然AppComponent是个全局的组件那我们就需要在Applcation中进行初始化的工作,那么它的生命周期就和Application一样长
首先是BaseApplication

public abstract class BaseApplication extends Application {
    static private BaseApplication mApplication;
    public LinkedList<BaseActiviy> mActivityList;
    private ClientModule mClientModule;
    private AppModule mAppModule;
    private  ServiceModule serviceModule;
    protected final String TAG = this.getClass().getSimpleName();


    @Override
    public void onCreate() {
        super.onCreate();
        mApplication = this;
        this.mClientModule = ClientModule//用于提供okhttp和retrofit的单列
                .buidler()
                .baseurl(getBaseUrl())
                .globeHttpHandler(getHttpHandler())
                .interceptors(getInterceptors())
                .build();
        this.mAppModule = new AppModule(this);//提供application
       this.serviceModule = new ServiceModule();
    }


    /**
     * 提供基础url给retrofit
     *
     * @return
     */
    protected abstract String getBaseUrl();


    public ServiceModule getServiceModule() {
        return serviceModule;
    }

    public ClientModule getClientModule() {
        return mClientModule;
    }

    public AppModule getAppModule() {
        return mAppModule;
    }

    /**
     * 这里可以提供一个全局处理http响应结果的处理类,
     * 这里可以比客户端提前一步拿到服务器返回的结果,可以做一些操作,比如token超时,重新获取
     * 默认不实现,如果有需求可以重写此方法
     *
     * @return
     */
    protected GlobeHttpHandler getHttpHandler() {
        return null;
    }

    /**
     * 用来提供interceptor,如果要提供额外的interceptor可以让子application实现此方法
     *
     * @return
     */
    protected Interceptor[] getInterceptors() {
        return null;
    }

    /**
     * 返回上下文
     *
     * @return
     */
    public static Context getContext() {
        return mApplication;
    }

}

我们的Application:App

public class App  extends BaseApplication{

    private AppComponent appComponent;

    @Override
    public void onCreate() {
        super.onCreate();
        appComponent = DaggerAppComponent.builder().clientModule(getClientModule()).appModule(getAppModule()).serviceModule(getServiceModule()).build();

    }

    @Override
    protected String getBaseUrl() {
        return API.BASE_URL;
    }

    public AppComponent getAppComponent() {
        return appComponent;
    }

}

在这里我们完成了AppComponent的初始化工作。从这我们可以看出App我们可以通过getAppComponent拿到AppComponent;

LoginComponent

@ActivityScope
@Component(modules = LoginModule.class,dependencies = AppComponent.class)
public interface LoginComponent {
    public void inject(MainActivity activity);
}

此组件是Login的工厂管理员,从图上可以看出,它不但管理着LoginModule,而且还依赖AppComponent,就是说他能够提供 Application,ApiService,loginModel,LoginContract.View(这个是通过构造方法传进来的),从而完成LoginPresenter的注入。当然我们是通过@inject构造方法注入的。不懂的请看dagger2的几种注入方式。

  • LoginModule
    注意其是dagger2中的Module,这是重点,从图中可以看出它提供了View和model,看代码,初始化过程是LoginContract使我们通过构造方法传入过来的,而ApiService是有上个AppCompoent提供。然后就完成了LoginContract.Model的初始化。
@Module
public class LoginModule {
    private LoginContract.View view;
    public LoginModule(LoginContract.View view) {
        this.view = view;
    }
    @ActivityScope
    @Provides
    LoginContract.View  providerContract() {
        return  view;
    }
    @ActivityScope
    @Provides
    LoginContract.Model providerModel(ApiService service){
        return  new LoginModel(service);
    }
}
  • LoginModel
    注意其是我们MVP中的Model,我们首先分析下,在loginModel中我们要联网请求,必然需要ApiService,而ApiSevice,是不是我们在ServiceModule,中是不是已经初始化好了,拿来用就好了。代码如下:
    BaseModel
public class BaseModel {
    public BaseModel() {
    }
    private ApiService apiService;

    public BaseModel(ApiService apiService) {
        this.apiService = apiService;
    }

    public ApiService getApiService() {
        return apiService;
    }
}

LoginModel

public class LoginModel extends BaseModel implements LoginContract.Model {
    public LoginModel(ApiService service) {
        super(service);
    }
    @Override
    public Observable<_User.LoginResult> login(String name, String password) {
        _User user = new _User();
        user.setUsername(name);
        user.setPassword(password);
        return getApiService().login(user).compose(RxsRxSchedulers.<_User.LoginResult>io_main());
    }
}

我们需要ApiService进行联网请求,所以我们要传进来一个ApiService对象。在LoginModule中我们初始化了这个LoginModel.

  • LoginPresenter

    首先是BasePresenter

public class BasePresenter<M extends IModel, V extends IView> implements Ipresenter {
    protected final String TAG = this.getClass().getSimpleName();
    protected M mModel;
    protected V mView;
    public BasePresenter() {
    }
    public BasePresenter(M model, V mView) {
        this.mModel = model;
        this.mView = mView;
        onStart();
    }
    public M getmModel() {
        return mModel;
    }
    public V getmView() {
        return mView;
    }
    public BasePresenter(V rootView) {
        this.mView = rootView;
        onStart();
    }
    public void onStart() {
    }

LoginPresenter

@ActivityScope
public class LoginPresenter extends BasePresenter<LoginContract.Model,LoginContract.View> {
    @Inject
    public LoginPresenter(LoginContract.Model model, LoginContract.View mView) {
        super(model, mView);
    }
    public void login(String name, String password){
        getmModel().login(name,password).subscribe(new Action1<_User.LoginResult>() {
            @Override
            public void call(_User.LoginResult loginResult) {

                Log.e(TAG, "call() called with: loginResult = [" + loginResult + "]");
                getmView().loginSucess();

            }
        }, new Action1<Throwable>() {
            @Override
            public void call(Throwable throwable) {
                Log.e(TAG, "call() called with: throwable = [" + throwable + "]");
                getmView().loginFailed();
            }
        });

    }
}

我们看到我们通过@inject构造方法完成LoginPresenter的初始化操作。LoginPresenter是怎样初始化的呢?当初始化该构造方法的时候里面有两个参数LoginContract.Model 和LoginContract.View,我们知道这两个参数初始化在LoginModule完成的也就完成了LoginPresenter的初始化。

  • MainActivity
    目标类也就是我们要注入的目的地
    首先看BaseActivity
public abstract class BaseActiviy <p extends BasePresenter> extends AppCompatActivity{
    @Inject
    protected  p  mPresenter;
    private App application;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        application = ((App) getApplication());
        setContentView(getContentViewId());
        componentInject(application.getAppComponent());//依赖注入
        initData();
    }
    protected abstract void componentInject(AppComponent appComponent);

componentInject(AppComponent appComponent)方法传入了我们需要的AppComponent;
MainActivity
初始化

@Override
    protected void componentInject(AppComponent appComponent) {
      DaggerLoginComponent.builder().appComponent(appComponent).loginModule(new       LoginModule(this)).build().inject(this);
    }

在此方法中完成了LoginComponent的初始化,并注入目标类中。

具体注入过程

  1. 首先是在BaseActivity中的 @Inject
    protected p mPresenter;此时会在LoginModule中查找对应的LoginPresenter,没有的话会从查找对应的构造方法,我们这里没有所有知道了加了@inject注释的构造方法。

  2. 找到

@Inject
    public LoginPresenter(LoginContract.Model model, LoginContract.View mView) {
        super(model, mView);
    }

构造方法里面面有两个参数LoginContract.Model,LoginContract.View,那就初始化这两个对象也就知道了LoginModule

  1. 在LoginModule中我们看到LoginContract.View 是我们通过构造方法传进来的,我们在初始化LoginComponent的时候
 DaggerLoginComponent.builder().appComponent(appComponent).loginModule(new LoginModule(this)).build().inject(this);

new LoginModule(this))传进来了这个this就是我们的Activity也就是我们的View.对于LoginContract.Model我们发现提供这个对象的方法里面有个参数是ApiService,那么它在哪里初始化的呢?我们发现在我们的LoginComponent依赖于AppComponet,而AppComponent暴露了APiService对象,我们也就查找到了ServiceModule.

  1. 在ServiceModule中我们发现其提供了一个返回值为ApiServce的方法,里面需要传入Retorfit对象。这个对象在哪里初始化的呢,因为AppComponent管理着ServiceModule,ClientModule,我们发现了ClientModule提供了Retofit对象。
  2. 在ClientModule中我们找到了一个加了@providers注解返为Retofit的方法
 @Singleton
    @Provides
    Retrofit provideRetrofit(OkHttpClient client, HttpUrl httpUrl) {
        final Retrofit.Builder builder = new Retrofit.Builder();
        return configureRetrofit(builder, client, httpUrl);
    }

里面需要传入OkHttpClient,HttpUrl对象。他们是怎么初始化的呢。在当前的ClientModule我们又发现了

  @Singleton
    @Provides
    OkHttpClient provideClient(Cache cache, Interceptor intercept) {
        final OkHttpClient.Builder okHttpClient = new OkHttpClient.Builder();
        return configureClient(okHttpClient, cache, intercept);
    }
@Singleton
    @Provides
    HttpUrl provideBaseUrl() {
        return mApiUrl;
    }

里面待参数的依次查找完成初始化工作,这里就不写了。基本就完成了所有的注入过程,其他没写到的请大家见谅。

当然这些工作不是我们做的是有Dagger2自动生成代码完成的,想要知道原理的可以看前面基础部分的原理。

源码传入门

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 160,585评论 4 365
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,923评论 1 301
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 110,314评论 0 248
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,346评论 0 214
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,718评论 3 291
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,828评论 1 223
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 32,020评论 2 315
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,758评论 0 204
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,486评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,722评论 2 251
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,196评论 1 262
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,546评论 3 258
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,211评论 3 240
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,132评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,916评论 0 200
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,904评论 2 283
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,758评论 2 274

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,105评论 18 139
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,296评论 18 399
  • 一、简介 Retrofit是Square公司开发的一款针对Android网络请求的框架,Retrofit2底层基于...
    Devil不加V阅读 508评论 0 0
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 170,585评论 25 707
  • 月影云遮 树翳穿梭 你望月 亦见云 云不见月现 树影斓 你说黑色不再纯粹 直发也开始像水鬼 ​​​
    笨蛋魔仙阅读 130评论 0 0