mvp框架学习实战代码(配合retrofit+dagger2+rxjava)

【转载请标明出处http://blog.csdn.net/sw5131899/article/details/51860922,谢谢】


最近一直在学习框架的搭建和使用,对于mvp,很多开发者有自己的独特见解,褒贬不一。不过我还是觉得它有学习的必要。在某些大项目上,使用mvp可以方便后期的代码维护和更新。废话不多说,开始进入正题。
首先是了解这些技术,我推荐几个个人觉得比较好的文档。
rxjava:http://blog.csdn.net/sw5131899/article/details/52064431
dagger2:http://blog.csdn.net/sw5131899/article/details/51839172
retrofit:http://blog.csdn.net/u014165119/article/details/49280779
这些都是基础的知识,那么开始框架的搭建。
首先,导入gradle。为了避免麻烦,我直接把gradle整个文档的内容粘出来。
</pre><pre name="code" class="java">apply plugin: 'com.android.application'
apply plugin: 'com.neenbedankt.android-apt'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.3"

    defaultConfig {
        applicationId "com.abings.daager2demo"
        minSdkVersion 19
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    lintOptions {
        warning 'InvalidPackage'
    }
}
buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.0-alpha1'
        classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
    }
}
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.4.0'
    apt 'com.google.dagger:dagger-compiler:2.2'
    provided 'org.glassfish:javax.annotation:10.0-b28'
    compile 'com.google.dagger:dagger:2.2'
    compile 'com.jakewharton:butterknife:7.0.1'
    compile 'com.google.code.gson:gson:2.6.2'
    compile 'com.squareup.retrofit:retrofit:2.0.0-beta2'
    compile 'com.squareup.retrofit2:converter-gson:2.+'
    compile 'io.reactivex:rxandroid:1.1.0'
    compile "com.squareup.retrofit:adapter-rxjava:2.0.0-beta2"
    compile "com.squareup.okhttp:okhttp:2.7.0"
}
配置dagger2,创建module和componnet。

创建appModule

@Module
public class AppModule {
    private Application application;

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

    @Singleton
    @Provides
    public Application providesApplication(){
        return application;
    }

    @Provides
    @Singleton
    APIService provideAPIService() {
        return RetrofitUtils.createApi(RxJavaCallAdapterFactory.create());
    }
}
appModule提供application的实例和APIService的实例,要保证它们是全局的即单例。加上@Singleton确定作用范围。

创建applicationComponent

@Singleton
@Component(modules = AppModule.class)
public interface ApplicationComponent {
    ActivityComponent plus(ActivityModule activityModule);
    DataManager dataManager();
}
Componnet相当于一个桥梁,将ActivityComponent作为其子Component。

创建PerActivity的scope

@Scope
@Retention(RetentionPolicy.RUNTIME)
public @interface PerActivity {
}

@Scope and @Singleton
这个注解是用来划分作用域的,标记当前对象使用范围。
比如限制对象只能在所有Activity中使用,或者只能在Application中使用,或者只能在Fragment中使用

@Singleton 单例模式全局共用一个对象 就是@Scope的一个实现

同理

@PerActivity
@Subcomponent(modules = ActivityModule.class)
public interface ActivityComponent {
    void inject(LoginActivity loginActivity);
    void inject(AActivity aActivity);
}
@Module
public class ActivityModule {
    private Activity mActivity;

    public ActivityModule(Activity activity){
        mActivity = activity;
    }

    @PerActivity
    @Provides
    public Activity providesActivity(){
        return mActivity;
    }
}
现在需要一个App全局类, 提供ActivityComponent对象。

public class App extends Application {
    private static ApplicationComponent applicationComponent;
    private ActivityComponent activityComponent;

    @Inject
    DataManager mDataManager;
    public static App get(Context context){
        return (App) context.getApplicationContext();
    }

    @Override
    public void onCreate() {
        super.onCreate();
        applicationComponent = DaggerApplicationComponent.builder().appModule(new AppModule(this)).build();
    }

    public void createActivityComponent(Activity activity){
        activityComponent = applicationComponent.plus(new ActivityModule(activity));
    }


    public ActivityComponent getActivityComponent(){
        return activityComponent;
    }

    public void releaseActivityComponent(){
        activityComponent = null;
    }


}
dagger所需的配置差不多完成了。接下来就是rxjava和retrofit的配置使用了。

public interface APIService {
    @GET("list/{page}")
    Observable<JSONObject> getDatas(@Path("page")int page);
}
public class RetrofitUtils {

    public static final String BASE_URL = "http://v3.wufazhuce.com:8000/api/movie/";
    public static Retrofit singleton;
    public static <T> T createApi(Class<T> clazz, Interceptor interceptor, RxJavaCallAdapterFactory factory) {
        //if (singleton == null) {
        synchronized (RetrofitUtils.class) {
            if (singleton == null) {
                Retrofit.Builder builder = new Retrofit.Builder()
                        .baseUrl(BASE_URL)
                                //.addConverterFactory(FastJsonConverterFactory.create())
                        .addConverterFactory(JsonConverterFactory.create());
                // .addConverterFactory(FastJsonConvertFactory.create());
                if (interceptor != null) {
                    builder.client(createInterceptor(interceptor));
                }
                if (factory != null) {
                    builder.addCallAdapterFactory(factory);
                }
                singleton = builder.build();
            }
        }
        return singleton.create(clazz);
    }


    public static <T> APIService createApi(RxJavaCallAdapterFactory factory) {
        return createApi(APIService.class, null, factory);
    }

    private static OkHttpClient createInterceptor(Interceptor interceptor) {
        OkHttpClient client = new OkHttpClient();
        client.networkInterceptors().add(interceptor);
        return client;
    }
}
这里想要将retrofit的实例通过dagger提供给下层使用,不用每次都创建retrofit对象。

接下来搭建mvp框架。

public abstract class BaseActivity extends AppCompatActivity{

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(setlayoutId());
        App.get(this).createActivityComponent(this);
        inject();
        initEvents(savedInstanceState);
    }

    protected abstract int setlayoutId();
    protected abstract void inject();
    protected abstract void initEvents(Bundle savedInstanceState);

}
public interface IBaseView<T> {
    void showMessage(String mes);
}
public interface Precenter<T extends IBaseView> {
    void attachView(T mvpView);
    void detachView();
}
具体使用mvp

public class LoginActivity extends BaseActivity implements LoginMvpView {


    @Inject
    LoginPecenter loginPecenter;


    @Bind(R.id.listview)
    ListView listView;

    @Override
    protected int setlayoutId() {
        return R.layout.activity_login;
    }

    @Override
    protected void inject() {
        App.get(this).getActivityComponent().inject(this);
        loginPecenter.attachView(this);
    }

    @Override
    protected void initEvents(Bundle savedInstanceState) {
        ButterKnife.bind(this);
    }


    @Override
    public void showMessage(String mes) {
        Toast.makeText(LoginActivity.this, mes, Toast.LENGTH_SHORT).show();
    }

    @OnClick(R.id.button)
    public void toA(){
//        startActivity(new Intent(this, AActivity.class));
        loginPecenter.loadData(0);
    }


    @Override
    public void showData(List list) {

    }
}
public interface LoginMvpView extends IBaseView {
    void showData(List list);
}
public class LoginPecenter implements Precenter<LoginMvpView> {

    private LoginMvpView mvpView;
    private final DataManager dataManager;
    private Subscription subscription;

    @Inject
    public LoginPecenter(DataManager dataManager){
        this.dataManager = dataManager;
    }

    @Override
    public void attachView(LoginMvpView mvpView) {
        this.mvpView = mvpView;
    }

    @Override
    public void detachView() {
        mvpView = null;
        if (subscription != null){
            subscription.unsubscribe();
        }
    }

    public void loadData(int page){
        subscription = dataManager.getdatas(page).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<JSONObject>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(JSONObject result) {
                Log.i("TAG00",result.toString());
                Gson gson = new Gson();
                listBean listBean = gson.fromJson(result.toString(), listBean.class);
                //省略更新UI逻辑。。
            }
        });

    }

}
在提供APIService实例的时候,需要一个类作为中转。API是接口,不能提供实例。所以创建一个Datamanager

@Singleton
public class DataManager {
    private final APIService apiService;

    @Inject
    public DataManager(APIService apiService){
        this.apiService = apiService;
    }

    public Observable<JSONObject> getdatas(int page) {
        return apiService.getDatas(page);
    }
}
重点的类也就这些了,其实我也不能为大家讲解清楚,只能意会不能言传,大家多看看源码,有利于学习提高。大家一起加油。

框架在开发中有着不可取代的地位,所以值得我们下功夫去学习。


附上git源码:

https://github.com/SingleShu/MvpRetrofitDagger



















  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值