Dagger2在MVP中的應(yīng)用
轉(zhuǎn)載說(shuō)明出處:http://blog.csdn.net/a15286856575/article/details/53405630
需要基礎(chǔ)
建議把基礎(chǔ)學(xué)會(huì)再看下面文章好理解點(diǎn)。
為什么MVP中要用Dagger2?
我們首先看一下傳統(tǒng)的mvp有什么缺點(diǎn)?
-
presenter在Activity的耦合
我們知道在傳統(tǒng)的MVP中Preseter是在Activity中初始化的,也就是顯式的new了一個(gè)對(duì)象,那么這里面在這個(gè)Activity中就有了耦合在里面。為什么會(huì)有耦合呢?
- 場(chǎng)景1: 假如你的項(xiàng)目中多次用到了這個(gè)Presetner,現(xiàn)在有這么個(gè)需求,這個(gè)Presenter依賴某個(gè)對(duì)象,需要在構(gòu)造方法中傳入這個(gè)對(duì)象,我們是不是要找到所有找到所有初始化這個(gè)Presenter的對(duì)象,然后去修改它,小項(xiàng)目還可以如果是大項(xiàng)目,我們是不是要找到所有的去修改。這就產(chǎn)生了耦合。怎么解決?Daggger2是個(gè)依賴注入框架,當(dāng)前的Activity不用關(guān)心Presenter,是怎么創(chuàng)建的,具體的創(chuàng)建交給module.我們只需要修改module. .
- 場(chǎng)景2:假如Presenter需要對(duì)象A,對(duì)象A需要對(duì)象B,對(duì)象B需要對(duì)象C,我們是不是先C c= new B(),B b = new B(c),A a = new A(B) 然后在初始化Presenter。像這種情況,我們是不是每次都需要這樣寫(xiě),在Activity中還要關(guān)系他們的創(chuàng)建順序。很繁瑣,用Dagger2就可以解決這個(gè)問(wèn)題。我們通過(guò)依賴注入,注入我們需要的對(duì)象,就大功告成了。
-
model在Presenter中的耦合
傳統(tǒng)的的mvp中的model是在Presenter中進(jìn)行初始化的,這里面也是顯示的new了一個(gè)對(duì)象。同樣也會(huì)有一個(gè)耦合在里面。
- 場(chǎng)景1:多個(gè)Presenter用了同一個(gè)model類,有同樣的需求,model需要傳入一個(gè)對(duì)象,我們是不是要找到用了這個(gè)model的所有Presenter,一個(gè)一個(gè)修改。里面是不是有耦合。同樣我們可以通過(guò)dagger2注入model,在dagger2的module修改這個(gè)model就行了。
- 場(chǎng)景2:初始化一個(gè)Model,需要對(duì)象A,對(duì)象A需要對(duì)象B,對(duì)象B需要對(duì)象C,我們是不是先C c= new B(),B b = new B(c),A a = new A(B),然后初始化Model。我們?cè)趯?duì)model進(jìn)行重用的時(shí)候,每次都要這樣做很繁瑣,通過(guò)dagger2中提供的創(chuàng)建的Module,我們可以注入這個(gè)model,是不是很省事。
注意module是Dagger2中的,model是mvp中的
當(dāng)然Dagger2不僅僅局限于MVP,在有耦合的地方都可以用。
Dagger2在MVP中的具體實(shí)現(xiàn)
架構(gòu)思路:對(duì)于上面兩種情況。他們可以有同一個(gè)Module提供,那我們就可以有一套依賴體系實(shí)現(xiàn),例如登錄,我們LoginModule提供Presenter和Model,LoginComponent負(fù)責(zé)注入,就行了。但是我們還需要一個(gè)全局的AppModule,提供OkHttpClient ,Sevivce,Retofit。然后讓LoginComponent依賴他就行了。那么我們?cè)贚oginComponent,就能夠拿到所有的Module.如圖:
我們需要兩個(gè)Component:
AppComponent
AppCompponet是在Applcation中初始化的所有是個(gè)全局的Component代碼如下
@Singleton
@Component(modules = {AppModule.class, ClientModule.class, ServiceModule.class})
public interface AppComponent {
Application Application();
ApiService apiService();
}
這個(gè)組件相當(dāng)于工廠管理員,他管理著AppModule,ClentModule,ServiceModule
通過(guò)他我們能找到這些Module所提供的實(shí)例。如果在其他Component依賴此Component,我們有需要那些module所提供的實(shí)例,那么我們就需要在AppComponent暴露這些對(duì)象,在這里我們暴露了Application ApiService;
- AppModule 主要提供Application對(duì)象。
@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對(duì)象.其中包括了配置我們需要的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: 設(shè)置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)//設(shè)置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);//設(shè)置緩存路徑和大小
}
/**
* 提供緩存地址
*/
@Singleton
@Provides
File provideCacheFile(Application application) {
return DataHelper.getCacheFile(application);
}
@Singleton
@Provides
Interceptor provideIntercept() {
return new RequestIntercept(mHandler);//打印請(qǐng)求信息的攔截器
}
/**
* 配置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)//設(shè)置緩存
.addNetworkInterceptor(intercept);
if (mInterceptors != null && mInterceptors.length > 0) {//如果外部提供了interceptor的數(shù)組則遍歷添加
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) {//基礎(chǔ)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) {//用來(lái)處理http響應(yīng)結(jié)果
this.handler = handler;
return this;
}
public Buidler interceptors(Interceptor[] interceptors) {//動(dòng)態(tài)添加任意個(gè)interceptor
this.interceptors = interceptors;
return this;
}
public ClientModule build() {
if (apiUrl == null) {
throw new IllegalStateException("baseurl is required");
}
return new ClientModule(this);
}
}
}
在ClientModule中我們找到了一個(gè)加了@providers注解返為Retofit的方法
@Singleton
@Provides
Retrofit provideRetrofit(OkHttpClient client, HttpUrl httpUrl) {
final Retrofit.Builder builder = new Retrofit.Builder();
return configureRetrofit(builder, client, httpUrl);
}
里面需要傳入OkHttpClient,HttpUrl對(duì)象。他們是怎么初始化的呢。在當(dāng)前的ClientModule我們又發(fā)現(xiàn)了
@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;
}
里面待參數(shù)的依次查找完成初始化工作,這里就不寫(xiě)了
- ServiceModule 主要是提供ApiSevice對(duì)象
@Module
public class ServiceModule {
@Singleton
@Provides
ApiService provideCommonService(Retrofit retrofit) {
return retrofit.create(ApiService.class);
}
}
ApiService初始化需要一個(gè)Retofit,這個(gè)Retrofit是有
- AppComponent初始化
既然AppComponent是個(gè)全局的組件那我們就需要在Applcation中進(jìn)行初始化的工作,那么它的生命周期就和Application一樣長(zhǎng)
首先是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();
}
/**
* 提供基礎(chǔ)url給retrofit
*
* @return
*/
protected abstract String getBaseUrl();
public ServiceModule getServiceModule() {
return serviceModule;
}
public ClientModule getClientModule() {
return mClientModule;
}
public AppModule getAppModule() {
return mAppModule;
}
/**
* 這里可以提供一個(gè)全局處理http響應(yīng)結(jié)果的處理類,
* 這里可以比客戶端提前一步拿到服務(wù)器返回的結(jié)果,可以做一些操作,比如token超時(shí),重新獲取
* 默認(rèn)不實(shí)現(xiàn),如果有需求可以重寫(xiě)此方法
*
* @return
*/
protected GlobeHttpHandler getHttpHandler() {
return null;
}
/**
* 用來(lái)提供interceptor,如果要提供額外的interceptor可以讓子application實(shí)現(xiàn)此方法
*
* @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我們可以通過(guò)getAppComponent拿到AppComponent;
LoginComponent
@ActivityScope
@Component(modules = LoginModule.class,dependencies = AppComponent.class)
public interface LoginComponent {
public void inject(MainActivity activity);
}
此組件是Login的工廠管理員,從圖上可以看出,它不但管理著LoginModule,而且還依賴AppComponent,就是說(shuō)他能夠提供 Application,ApiService,loginModel,LoginContract.View(這個(gè)是通過(guò)構(gòu)造方法傳進(jìn)來(lái)的),從而完成LoginPresenter的注入。當(dāng)然我們是通過(guò)@inject構(gòu)造方法注入的。不懂的請(qǐng)看dagger2的幾種注入方式。
- LoginModule
注意其是dagger2中的Module,這是重點(diǎn),從圖中可以看出它提供了View和model,看代碼,初始化過(guò)程是LoginContract使我們通過(guò)構(gòu)造方法傳入過(guò)來(lái)的,而ApiService是有上個(gè)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中我們要聯(lián)網(wǎng)請(qǐng)求,必然需要ApiService,而ApiSevice,是不是我們?cè)赟erviceModule,中是不是已經(jīng)初始化好了,拿來(lái)用就好了。代碼如下:
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進(jìn)行聯(lián)網(wǎng)請(qǐng)求,所以我們要傳進(jìn)來(lái)一個(gè)ApiService對(duì)象。在LoginModule中我們初始化了這個(gè)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();
}
});
}
}
我們看到我們通過(guò)@inject構(gòu)造方法完成LoginPresenter的初始化操作。LoginPresenter是怎樣初始化的呢?當(dāng)初始化該構(gòu)造方法的時(shí)候里面有兩個(gè)參數(shù)LoginContract.Model 和LoginContract.View,我們知道這兩個(gè)參數(shù)初始化在LoginModule完成的也就完成了LoginPresenter的初始化。
- MainActivity
目標(biāo)類也就是我們要注入的目的地
首先看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的初始化,并注入目標(biāo)類中。
具體注入過(guò)程
首先是在BaseActivity中的 @Inject
protected p mPresenter;此時(shí)會(huì)在LoginModule中查找對(duì)應(yīng)的LoginPresenter,沒(méi)有的話會(huì)從查找對(duì)應(yīng)的構(gòu)造方法,我們這里沒(méi)有所有知道了加了@inject注釋的構(gòu)造方法。找到
@Inject
public LoginPresenter(LoginContract.Model model, LoginContract.View mView) {
super(model, mView);
}
構(gòu)造方法里面面有兩個(gè)參數(shù)LoginContract.Model,LoginContract.View,那就初始化這兩個(gè)對(duì)象也就知道了LoginModule
- 在LoginModule中我們看到LoginContract.View 是我們通過(guò)構(gòu)造方法傳進(jìn)來(lái)的,我們?cè)诔跏蓟疞oginComponent的時(shí)候
DaggerLoginComponent.builder().appComponent(appComponent).loginModule(new LoginModule(this)).build().inject(this);
new LoginModule(this))傳進(jìn)來(lái)了這個(gè)this就是我們的Activity也就是我們的View.對(duì)于LoginContract.Model我們發(fā)現(xiàn)提供這個(gè)對(duì)象的方法里面有個(gè)參數(shù)是ApiService,那么它在哪里初始化的呢?我們發(fā)現(xiàn)在我們的LoginComponent依賴于AppComponet,而AppComponent暴露了APiService對(duì)象,我們也就查找到了ServiceModule.
- 在ServiceModule中我們發(fā)現(xiàn)其提供了一個(gè)返回值為ApiServce的方法,里面需要傳入Retorfit對(duì)象。這個(gè)對(duì)象在哪里初始化的呢,因?yàn)锳ppComponent管理著ServiceModule,ClientModule,我們發(fā)現(xiàn)了ClientModule提供了Retofit對(duì)象。
- 在ClientModule中我們找到了一個(gè)加了@providers注解返為Retofit的方法
@Singleton
@Provides
Retrofit provideRetrofit(OkHttpClient client, HttpUrl httpUrl) {
final Retrofit.Builder builder = new Retrofit.Builder();
return configureRetrofit(builder, client, httpUrl);
}
里面需要傳入OkHttpClient,HttpUrl對(duì)象。他們是怎么初始化的呢。在當(dāng)前的ClientModule我們又發(fā)現(xiàn)了
@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;
}
里面待參數(shù)的依次查找完成初始化工作,這里就不寫(xiě)了。基本就完成了所有的注入過(guò)程,其他沒(méi)寫(xiě)到的請(qǐng)大家見(jiàn)諒。
當(dāng)然這些工作不是我們做的是有Dagger2自動(dòng)生成代碼完成的,想要知道原理的可以看前面基礎(chǔ)部分的原理。