Hot项目进行部分修改(加入Dagger2)

要是没有看过之前的MVP+Rxjava+Retrofit构建项目,最近在看Dagger2,网上资料也很多,并且在自己私下的项目中Hot运用(一个关于微信热门头条的分享),让我无耻的说一下
github地址,欢迎star。
这里就不介绍dagger的一些使用方法啊,这里有个很好的介绍dagger介绍。我现在在项目中使用了DataManager来管理数据(无论数据的来源),

/**
 * Created by wukewei on 16/7/12.
 * 这个类是管理app的数据来源无论从网络获取.内存.还是磁盘
 */
public class DataManager {

    private  HotApi mHotApi;
    private  CacheLoader cacheLoader;


    @Inject
    public DataManager(HotApi hotApi, CacheLoader cacheLoader) {
        this.mHotApi = hotApi;
        this.cacheLoader = cacheLoader;
    }

    /***
     * 获取分类的类型
     * @param
     * @param
     * @return
     */
    public List<String> getTabs() {
        List<String> tabs = new ArrayList<>();
        tabs.add("科技");
        tabs.add("美女");
        tabs.add("生活");
        tabs.add("娱乐");
        tabs.add("搞笑");
        tabs.add("宅男");
        return tabs;
    }

    /***
     * 获取列表
     * @param pn 页码
     * @param type 类别名称
     * @return
     */
    public Observable<List<Popular>> getPopular(int pn, String type) {
        return mHotApi.getPopular(pn, Constants.PAGE_SIZE, type)
                .compose(SchedulersCompat.applyIoSchedulers())
                .compose(RxResultHelper.handleResult())
                .doOnNext(populars -> {
                    if (pn == 1) {
                        ListPopular popular = new ListPopular(populars);
                        cacheLoader.upNewData(type, popular);
                    }
                });
    }

    /***
     * 获取缓存信息 默认只缓存第一页
     * @param type 类别名称
     * @param
     * @return
     */
    public Observable<List<Popular>> getCachePopular(String type) {
        NetworkCache<ListPopular> networkCache = new NetworkCache<ListPopular>() {
            @Override
            public Observable<ListPopular> get(String key, Class<ListPopular> cls) {
                return mHotApi.getPopular(1, Constants.PAGE_SIZE, type)
                        .compose(SchedulersCompat.applyIoSchedulers())
                        .compose(RxResultHelper.handleResult())
                        .flatMap(populars -> {
                            ListPopular popular = new ListPopular(populars);
                            return Observable.just(popular);
                        });
            }
        };

        return cacheLoader.asDataObservable(Constants.NEW_LIST + type, ListPopular.class, networkCache)
                .map(listPopular -> listPopular.data);
    }
}

1.AppModule的构造的对象和提供的依赖

/**
 * Created by wukewei on 16/7/19.
 */
@Module
public class AppModule {

    private App application;

    public AppModule(App application) {
        this.application = application;
    }


    @Provides
    @Singleton
    @ContextLife("Application")
    public App provideApp() {
        return application;
    }


    @Provides
    @Singleton
    OkHttpClient provideOkHttpClient() {
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        Interceptor apikey = chain -> chain.proceed(chain.request().newBuilder()
                .addHeader("apikey", Constants.Api_Key).build());

        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .readTimeout(Constants.HTTP_CONNECT_TIMEOUT, TimeUnit.MILLISECONDS)
                .connectTimeout(Constants.HTTP_CONNECT_TIMEOUT, TimeUnit.MILLISECONDS)
                .addInterceptor(apikey)
                .addInterceptor(loggingInterceptor)
                .build();

        return okHttpClient;
    }

    @Provides
    @Singleton
    HotApi provideHotApi(OkHttpClient okHttpClient) {
        Retrofit retrofit1 = new Retrofit.Builder()
                .baseUrl(Constants.Base_Url)
                .client(okHttpClient)
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        HotApi hotApi = retrofit1.create(HotApi.class);

        return hotApi;
    }

    @Provides
    @Singleton
    CacheLoader provideCacheLoader() {
        return CacheLoader.getInstance(application);
    }

    @Provides
    @Singleton
    DataManager provideDataManager(HotApi hotApi, CacheLoader cacheLoader) {
        return new DataManager(hotApi, cacheLoader);
    }


}

接下来的Component的注入的代码
2.ActivityComponent的代码:

/**
 * Created by wukewei on 16/7/19.
 */
@PerActivity
@Component(dependencies = AppComponent.class, modules = ActivityModule.class)
public interface ActivityComponent {

    DataManager getDataManager();

    Activity getActivity();

    void inject(MainActivity mainActivity);
    void inject(WebActivity webActivity);

}

3.FragmentComponent的代码

/**
 * Created by wukewei on 16/7/19.
 */
@PerFragment
@Component(dependencies = AppComponent.class, modules = FragmentModule.class)
public interface FragmentComponent {

    DataManager getDataManager();

    Activity getActivity();

    void inject(ItemFragment itemFragment);

}

之前在View 和P的关联在通过在p构造方法中传入,现在是使用调用p的attachView()方法。
4.现在BasePresenter设计

/**
 * Created by wukewei on 16/5/26.
 */
public abstract class BasePresenter<T extends IView> implements IPresenter<T> {

    protected Activity mActivity;
    protected T mView;
    protected CompositeSubscription mCompositeSubscription;
    protected DataManager dataManager;

    public BasePresenter(DataManager dataManager, Activity activity) {
        this.dataManager = dataManager;
        this.mActivity = activity;
    }

    @Override
    public void attachView(T view) {
        this.mView = view;
    }

    protected void handleError(Throwable throwable) {
        ToastUtil.showShort(mActivity, ErrorHanding.handleError(throwable));
    }

    protected void unSubscribe() {
        if (mCompositeSubscription != null) {
            mCompositeSubscription.unsubscribe();
        }
    }

    protected void addSubscribe(Subscription subscription) {
        if (mCompositeSubscription == null) {
            mCompositeSubscription = new CompositeSubscription();
        }
        mCompositeSubscription.add(subscription);
    }

    @Override
    public void detachView() {
        this.mView = null;
        unSubscribe();
    }
}

5.BaseActivity中的p之前需要自己new出来,现在加入了dagger2,通过注入的方式。

/**
 * Created by wukewei on 16/5/26.
 */
public abstract class BaseActivity<T extends IPresenter> extends AppCompatActivity implements IView {

    @Inject
    protected T mPresenter;
    protected Activity mContext;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayout());
        ButterKnife.bind(this);
        mContext = this;
        setupActivityComponent(App.getAppComponent(),new ActivityModule(this));
        mPresenter.attachView(this);
        initEventAndData();
    }

    protected void setCommonBackToolBack(Toolbar toolbar, String title) {
        toolbar.setTitle(title);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        toolbar.setNavigationOnClickListener(v -> onBackPressed());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);
        if (mPresenter != null) mPresenter.detachView();
    }

    /**
     * 依赖注入的入口
     * @param appComponent appComponent
     */
    protected abstract void setupActivityComponent(AppComponent appComponent, ActivityModule activityModule);

    protected abstract int getLayout();
    protected abstract void initEventAndData();
}

多了setupActivityComponent()方法这就是依赖注入的入口好比。

   @Override
    protected void setupActivityComponent(AppComponent appComponent, ActivityModule activityModule) {
        DaggerActivityComponent.builder()
                .appComponent(appComponent)
                .activityModule(activityModule)
                .build()
                .inject(this);
    }

这个项目是我私下自己在学习新的技术,并且运用在一起的项目,也是像对待产品一个对待这个app开发,后续会不断的学习和更新项目。本人也是个android小菜鸟,从最弱最弱的做起,要是觉得项目对你有帮助的话欢迎star,让我再啰嗦的说一下github地址

    原文作者:我想要有你在的未来
    原文地址: https://www.jianshu.com/p/38136b84734d
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞