面试技巧小技巧

手把手带你搭建Mvp+Dagger架构

2019-01-11  本文已影响80人  付凯强

0. 序言

1. 博文目录

2. 添加依赖

    implementation 'com.squareup.retrofit2:retrofit:2.5.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.5.0'
    implementation 'com.squareup.retrofit2:adapter-rxjava2:2.5.0'
    implementation 'io.reactivex.rxjava2:rxjava:2.2.4'
    implementation 'io.reactivex.rxjava2:rxandroid:2.1.0'
    implementation 'com.squareup.okhttp3:okhttp:3.12.0'
    implementation 'com.squareup.okhttp3:logging-interceptor:3.5.0'
    implementation 'com.trello.rxlifecycle2:rxlifecycle-android-lifecycle:2.2.1'

3. 创建项目基本目录

image.png

4. 实现Model

public class NewsInfo {
    private String reason;
    private ResultBean result;
    ...
    public static class ResultBean {
        private String stat;
        private List<DataBean> data;
        ...
        public static class DataBean {
            private String uniquekey;
            private String title;
            private String date;
            private String category;
            private String author_name;
            private String url;
            private String thumbnail_pic_s;
            private String thumbnail_pic_s02;
            private String thumbnail_pic_s03;
            ...
        }
    }
}
public interface NetTask {
    void execute(LifecycleProvider lifecycleProvider, String type, LoadTasksCallBack callBack);
}
public interface LoadTasksCallBack {
    void OnSuccess(NewsInfo newsInfo);
    void OnStart();
    void onFailed();
    void onFinish();
}
public class NewsInfoTask implements NetTask {

    private Disposable mDisposable;

    private NewsInfoTask() {

    }

    public static NewsInfoTask getInstance() {
        return NewsInfoTaskHolder.sNewsInfoFask;
    }

    private static class NewsInfoTaskHolder {
        private static final NewsInfoTask sNewsInfoFask = new NewsInfoTask();
    }

    @Override
    public void execute(LifecycleProvider lifecycleProvider,String type, final LoadTasksCallBack callBack) {

        RetrofitManager.getInstance().getRetrofit(Constant.BASEURL).create(NewsService.class)
                .getNewsInfo(type, BuildConfig.NewKey)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(lifecycleProvider.<Long>bindUntilEvent(Lifecycle.Event.ON_DESTROY))
                .subscribe(new Observer<NewsInfo>() {
                    @Override
                    public void onSubscribe(Disposable disposable) {
                        mDisposable= disposable;
                        callBack.OnStart();
                    }

                    @Override
                    public void onNext(NewsInfo newsInfo) {
                        callBack.OnSuccess(newsInfo);
                    }

                    @Override
                    public void onError(Throwable e) {
                        callBack.onFailed();
                    }

                    @Override
                    public void onComplete() {
                        callBack.onFinish();
                        mDisposable.dispose();
                    }
                });
    }
}

6. 定义契约接口NewsInfoContract:

public interface NewsInfoContract {
    interface Presenter{
        void getNewsInfo(LifecycleProvider lifecycleProvider, String type);
    }

    interface View {
        void setNewsInfo(NewsInfo newsInfo);
        void showLoading();
        void hideLoading();
        void showError();
    }
}

7. 实现Presenter

public class NewsInfoPresenter implements NewsInfoContract.Presenter,LoadTasksCallBack {
    private NetTask mNetTask;
    private NewsInfoContract.View mView;

    public NewsInfoPresenter(NetTask netTask,NewsInfoContract.View view) {
        mNetTask = netTask;
        mView = view;
    }

        @Override
    public void getNewsInfo(LifecycleProvider lifecycleProvider, String type) {
        mNetTask.execute(lifecycleProvider,type,this);
    }

    @Override
    public void OnSuccess(NewsInfo newsInfo) {
        mView.setNewsInfo(newsInfo);
    }

    @Override
    public void OnStart() {
        mView.showLoading();
    }

    @Override
    public void onFailed() {
        mView.showError();
        mView.hideLoading();
    }

    @Override
    public void onFinish() {
        mView.hideLoading();
    }
}  

6. 实现View

public class MainActivity extends AppCompatActivity implements NewsInfoContract.View {

    private NewsInfoContract.Presenter mPresenter = new NewsInfoPresenter(NewsInfoTask.getInstance(),this);
    LifecycleProvider<Lifecycle.Event> lifecycleProvider = AndroidLifecycle.createLifecycleProvider(this);
    private TextView mNew_Content;
    private Dialog mDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mNew_Content = findViewById(R.id.tv_content);
        mDialog = new ProgressDialog(this);
        mDialog.setTitle(R.string.dialog_get_info);
        findViewById(R.id.bt_get_news).setOnClickListener(v -> {
            mPresenter.getNewsInfo(lifecycleProvider,Constant.DEFAULT_TYPE);
        });
    }

    @Override
    public void setNewsInfo(NewsInfo newsInfo) {
        if (newsInfo != null && newsInfo.getResult() != null && newsInfo.getResult().getData() != null) {
            mNew_Content.setText(newsInfo.getResult().getData().get(0).getTitle());
        }
    }

    @Override
    public void showLoading() {
        mDialog.show();
    }

    @Override
    public void hideLoading() {
        if (mDialog.isShowing())
            mDialog.dismiss();
    }

    @Override
    public void showError() {
        Toast.makeText(this, R.string.toast_net_tip, Toast.LENGTH_SHORT).show();
    }

}

7. 补充网络配置代码

public class RetrofitManager {

    private static Retrofit sRetrofit = null;
    private static String sUrl = "";
    private static final int TIMEOUT = 20;

    private RetrofitManager() {
    }

    public static RetrofitManager getInstance() {
        return RetrofitManagerHolder.sInstance;
    }

    private static class RetrofitManagerHolder {
        private static final RetrofitManager sInstance = new RetrofitManager();
    }

    public Retrofit getRetrofit(String baseUrl) {
        sUrl = baseUrl;
        if (sRetrofit == null) {
            return create();
        } else {
            return sRetrofit;
        }
    }

    private Retrofit create() {

        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        if (BuildConfig.DEBUG) {
            loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        } else {
            loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BASIC);
        }

        OkHttpClient okHttpClient = new OkHttpClient.Builder().addInterceptor(loggingInterceptor)
                .connectTimeout(TIMEOUT,TimeUnit.SECONDS)
                .readTimeout(TIMEOUT, TimeUnit.SECONDS)
                .writeTimeout(TIMEOUT, TimeUnit.SECONDS)
                .retryOnConnectionFailure(true).build();

        sRetrofit = new Retrofit.Builder()
                .baseUrl(sUrl)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(okHttpClient)
                .build();
        return sRetrofit;
    }
}
public interface NewsService {

    @GET("toutiao/index")
    Observable<NewsInfo> getNewsInfo(@Query("type") String type, @Query("key")String key);
}

8. 适配Android28网络请求

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <base-config cleartextTrafficPermitted="true" />
</network-security-config>
android:networkSecurityConfig="@xml/network_security_config"

9. 添加Dagger2

9.0 分析

这里我们需要把NewsInfoTask和MainActivity注入到了Presenter中,把Presenter注入到了MainActivity中。

9.1 Dagger2实现NewsInfoTask单例
    private NewsInfoTask() {

    }

    public static NewsInfoTask getInstance() {
        return NewsInfoTaskHolder.sNewsInfoFask;
    }

    private static class NewsInfoTaskHolder {
        private static final NewsInfoTask sNewsInfoFask = new NewsInfoTask();
    }
@Module
public class NetTaskModule {
    @Singleton
    @Provides
    public NetTask provideNewsInfoTask(){
        return new NewsInfoTask();
    }
}

说明:生成NewsInfoTask的实例对象,并用@Singleton修饰。

@Singleton
@Component(modules = NetTaskModule.class)
public interface NetTaskComponent {
    NetTask getNetTask();
}

说明:
① NetTaskModule 中的方法provideNewsInfoTask用@Singleton修饰,NetTaskComponent也必须用@Singleton修饰。
② NetTaskComponent中不需要指明注入的目标,而需要提供实例对象的时候,可以用“NetTask getNetTask();”这种形式表示,指明返回的是NetTask,返回值很重要。

public class App extends Application {

    private NetTaskComponent mNetTaskComponent;

    @Override
    public void onCreate() {
        super.onCreate();
        mNetTaskComponent = DaggerNetTaskComponent.builder().build();
    }

    public static App get(Context context){
        return (App)context.getApplicationContext();
    }

    public NetTaskComponent getNetTaskComponent() {
        return mNetTaskComponent;
    }
}

说明:这里通过.builder().build()来获取NetTaskComponent。需要NewsInfoTask只通过NetTaskComponent,就可以保证NewsInfoTask对象的内存地址唯一了。

9.2 Presenter注入MainActivity
    @Inject
    public NewsInfoPresenter(NewsInfoContract.View view,NetTask netTask) {
        mView = view;
        mNetTask = netTask;
    }

说明:@Inject修饰构造方法意思是告诉Dagger2可以用这个构造方法构建NewsInfoPresenter。只有构造方法上有@Inject注解修饰,NewsInfoPresenter才可以对外提供实例对象。

public interface NewsInfoContract {
    interface Presenter{
        void getNewsInfo(LifecycleProvider lifecycleProvider, String type);
    }

    interface View {
        void setNewsInfo(NewsInfo newsInfo);
        void showLoading();
        void hideLoading();
        void showError();
        void setPresenter(NewsInfoPresenter presenter);
    }
}
    @Inject
    void setPresenter(){
        mView.setPresenter(this);
    }

说明:@Inject修饰方法的意思是方法注入,这里是把NewsInfoPresenter注入给MainActivity。方法注入是在构造方法后执行的。方法注入需要构造方法使用@Inject注解修饰,不然方法注入无法执行。

    @Inject
    NewsInfoPresenter mPresenter;

说明:@Inject修饰变量意思是NewsInfoPresenter需要依赖注入。

    @Override
    public void setPresenter(NewsInfoPresenter presenter) {
        mPresenter = presenter;
    }

综上:以上几步完成了Persenter注入到MainActivity。

9.3 NewsInfoTask和MainActivity注入到了Presenter

@Scope
@Documented
@Retention(RUNTIME)
public @interface ActivityScoped {
}
@Module
public class NewsInfoModule {

    private NewsInfoContract.View mView;

    public NewsInfoModule(NewsInfoContract.View view) {
        mView = view;
    }

    @Provides
    public NewsInfoContract.View provideNewsInfoContractView() {
        return mView;
    }

}

说明:这里是为了将NewsInfoContract.View注入给MainActivity。

@ActivityScoped
@Component(modules = NewsInfoModule.class,dependencies =NetTaskComponent.class)
public interface MainActivityComponent {
    void inject(MainActivity mainActivity);
}

说明:
① dependencies意思是把NetTaskComponent的内容也拿过来注入。
② @ActivityScoped之所以创建自定义Scope是因为如果dependencies中的NetTaskComponent用了@Singleton修饰,这里就不能使用@Singleton修饰了。

DaggerMainActivityComponent.builder().newsInfoModule(new NewsInfoModule(this))
                .netTaskComponent(App.get(this).getNetTaskComponent()).build().inject(this);

说明:因为Presenter需要两个参数,所以这里一句话就把需要的两个参数传入了Presenter。我们看下DaggerMainActivityComponent的源码:

    public Builder newsInfoModule(NewsInfoModule newsInfoModule) {
      this.newsInfoModule = Preconditions.checkNotNull(newsInfoModule);
      return this;
    }

    public Builder netTaskComponent(NetTaskComponent netTaskComponent) {
      this.netTaskComponent = Preconditions.checkNotNull(netTaskComponent);
      return this;
    }

说明:.newsInfoModule和.netTaskComponent接收Presenter需要的两个参数。然后看build():

public MainActivityComponent build() {
      if (newsInfoModule == null) {
        throw new IllegalStateException(NewsInfoModule.class.getCanonicalName() + " must be set");
      }
      if (netTaskComponent == null) {
        throw new IllegalStateException(NetTaskComponent.class.getCanonicalName() + " must be set");
      }
      return new DaggerMainActivityComponent(this);
    }

说明:这里把build()所在的Build传入了DaggerMainActivityComponent的构造方法,我们看下:

  private DaggerMainActivityComponent(Builder builder) {
    assert builder != null;
    initialize(builder);
  }

说明:再看下initialize方法:

this.provideNewsInfoContractViewProvider =
        NewsInfoModule_ProvideNewsInfoContractViewFactory.create(builder.newsInfoModule);

    this.getNetTaskProvider =
        new Factory<NetTask>() {
          private final NetTaskComponent netTaskComponent = builder.netTaskComponent;

          @Override
          public NetTask get() {
            return Preconditions.checkNotNull(
                netTaskComponent.getNetTask(),
                "Cannot return null from a non-@Nullable component method");
          }
        };

    this.newsInfoPresenterProvider =
        NewsInfoPresenter_Factory.create(
            newsInfoPresenterMembersInjector,
            provideNewsInfoContractViewProvider,
            getNetTaskProvider);

说明:newsInfoModule得到provideNewsInfoContractViewProvider,netTaskComponent得到getNetTaskProvider,然后把两者,放入NewsInfoPresenter_Factory.create方法中:

  public static Factory<NewsInfoPresenter> create(
      MembersInjector<NewsInfoPresenter> newsInfoPresenterMembersInjector,
      Provider<NewsInfoContract.View> viewProvider,
      Provider<NetTask> netTaskProvider) {
    return new NewsInfoPresenter_Factory(
        newsInfoPresenterMembersInjector, viewProvider, netTaskProvider);
  }

说明:再看NewsInfoPresenter_Factory

  public NewsInfoPresenter_Factory(
      MembersInjector<NewsInfoPresenter> newsInfoPresenterMembersInjector,
      Provider<NewsInfoContract.View> viewProvider,
      Provider<NetTask> netTaskProvider) {
    assert newsInfoPresenterMembersInjector != null;
    this.newsInfoPresenterMembersInjector = newsInfoPresenterMembersInjector;
    assert viewProvider != null;
    this.viewProvider = viewProvider;
    assert netTaskProvider != null;
    this.netTaskProvider = netTaskProvider;
  }

说明:用viewProvider封装了NewsInfoContract.View;用netTaskProvider封装了NetTask。他们调用给了get方法:

  @Override
  public NewsInfoPresenter get() {
    return MembersInjectors.injectMembers(
        newsInfoPresenterMembersInjector,
        new NewsInfoPresenter(viewProvider.get(), netTaskProvider.get()));
  }

说明:看到这里,你会清晰的看到NetTask和MainActivity注入到了Presenter,而这个get方法何时调用的呢?我们看下inject方法:

  @Override
  public void inject(MainActivity mainActivity) {
    mainActivityMembersInjector.injectMembers(mainActivity);
  }

说明:再接着看injectMembers方法:

    @Override
    public void injectMembers(MainActivity instance) {
      if (instance == null) {
        throw new NullPointerException("Cannot inject members into a null reference");
      }
      instance.mPresenter = mPresenterProvider.get();
    }

说明:mPresenterProvider是谁呢:

private final Provider<NewsInfoPresenter> mPresenterProvider;

说明:到这里会发现其实inject的目的就是把两个参数赋值给this中的presenter,而赋值离不开new,自然离不开构造方法,而构造方法那里也离不开@Inject。而这也正是Dagger2的原理所在,通过工厂方法把实例对象赋值给注入目标的用@Inject所修饰的成员变量。

10. 实现RetrofitManager单例

    private RetrofitManager() {
    }

    public static RetrofitManager getInstance() {
        return RetrofitManagerHolder.sInstance;
    }

    private static class RetrofitManagerHolder {
        private static final RetrofitManager sInstance = new RetrofitManager();
    }
    @Singleton
    @Provides
    public RetrofitManager provideRetrofitManager(){
        return new RetrofitManager();
    }
@Singleton
@Component(modules = NetTaskModule.class)
public interface NetTaskComponent {
    NetTask getNetTask();
    RetrofitManager getRetrofitManager();
}
public class App extends Application {

    private static NetTaskComponent mNetTaskComponent;

    @Override
    public void onCreate() {
        super.onCreate();
        mNetTaskComponent = DaggerNetTaskComponent.builder().build();
    }

    public static NetTaskComponent getNetTaskComponent() {
        return mNetTaskComponent;
    }
}

说明:之前的方式需要传入Context,但是NewsInfoTask中并没有Context,所以我们这里修改为static,因为是单例模式,从创建就开始存在直到App应用程序退出,所以不会有内存泄露的情况。

11. 代码下载地址:

https://github.com/OnlyYouMyLove/Mvp_Dagger2
这篇文章的Model和View是通过Build参数的方式通过Presenter的构造方法注入;还可以Model单独注入到Presenter,View通过Build参数的方式注入到Presenter,这里不再给出代码,感兴趣的可以留言。

12. 后续

如果大家喜欢这篇文章,欢迎点赞;如果想看更多 Dagger 方面的技术,欢迎关注!

上一篇下一篇

猜你喜欢

热点阅读