美文网首页
RxJava+Retrofit+OkHttp + MVP

RxJava+Retrofit+OkHttp + MVP

作者: 毕加森 | 来源:发表于2017-10-09 14:04 被阅读0次
    一、MvpFile(mvp)
    • BaseView
    public interface BaseView {
        Context getContext();
    }
    
    • BasePresenter
    public interface BasePresenter<V extends BaseView> {
        void attachView(V view);
        void detachView();
    }
    
    • BasePresenterImpl
    public class BasePresenterImpl<V extends BaseView> implements BasePresenter<V> {
    
        protected V mView;
    
        @Override
        public void attachView(V view) {
            mView = view;
        }
    
        @Override
        public void detachView() {
            mView = null;
        }
    }
    
    • MVPBaseActivity
    public abstract class MVPBaseActivity<V extends BaseView, T extends BasePresenterImpl<V>> extends AppCompatActivity implements BaseView {
    
        public T mPresenter;
    
        @Override
        protected void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            mPresenter = getInstance(this, 1);
            mPresenter.attachView((V) this);
        }
    
        @Override
        protected void onDestroy() {
            super.onDestroy();
            if (mPresenter != null)
                mPresenter.detachView();
        }
    
        @Override
        public Context getContext() {
            return this;
        }
    
        public <T> T getInstance(Object o, int i) {
            try {
                return ((Class<T>) ((ParameterizedType) (o.getClass()
                        .getGenericSuperclass())).getActualTypeArguments()[i])
                        .newInstance();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (ClassCastException e) {
                e.printStackTrace();
            }
            return null;
        }
    }
    
    • MVPBaseFragment
    public abstract class MVPBaseFragment<V extends BaseView, T extends BasePresenterImpl<V>> extends Fragment implements BaseView {
    
        public T mPresenter;
    
        @Override
        public void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            mPresenter = getInstance(this, 1);
            mPresenter.attachView((V) this);
        }
    
        @Override
        public void onDestroy() {
            super.onDestroy();
            if (mPresenter != null)
                mPresenter.detachView();
        }
    
        @Override
        public Context getContext() {
            return super.getContext();
        }
    
        public <T> T getInstance(Object o, int i) {
            try {
                return ((Class<T>) ((ParameterizedType) (o.getClass()
                        .getGenericSuperclass())).getActualTypeArguments()[i])
                        .newInstance();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (ClassCastException e) {
                e.printStackTrace();
            } catch (java.lang.InstantiationException e) {
                e.printStackTrace();
            }
            return null;
        }
    }
    
    二、MvpFile(loginactivity)
    • LoginContract
    public class LoginContract {
    
        interface View extends BaseView {
        }
    
        interface Presenter extends BasePresenter<View> {
        }
    }
    
    • LoginPresenter
    public class LoginPresenter extends BasePresenterImpl<LoginContract.View> implements LoginContract.Presenter {
    }
    
    • LoginActivity
    public class LoginActivity extends MVPBaseActivity<LoginContract.View, LoginPresenter> implements LoginContract.View {
    }
    
    三、Rx-Retrofit
    • 根目录下build.gradle添加仓地址:
    allprojects {
        repositories {
            jcenter()
            maven { url 'https://jitpack.io' }
        }
    }
    
    • app目录下build.gradle添加依赖库:
    dependencies {
        compile 'com.github.wzgiceman:Rx-Retrofit:v1.0'
    }
    
    • 添加Application并在AndroidManifest中注册
    public class MyApplication extends Application {
    
        // TODO 若BaseUrl全局唯一的需在此处设置,不唯一则设"",并在具体Api中设置BaseUrl
        public static final String APP_BASE_URL = "";
    
        @Override
        public void onCreate() {
            super.onCreate();
            RxRetrofitApp.init(this, APP_BASE_URL);
        }
    
    }
    
    • 添加BaseActivity并继承RxAppCompatActivity
    public class BaseActivity extends RxAppCompatActivity {
    
        protected ProgressDialog dialog;
    
        @Override
        protected void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            if (dialog == null) {
                dialog = new ProgressDialog(this);
                dialog.setCancelable(false);
            }
        }
    
        protected void showLoading() {
            if (dialog != null && !dialog.isShowing()) {
                dialog.show();
            }
        }
    
        protected void hideLoading() {
            if (dialog != null && dialog.isShowing()) {
                dialog.dismiss();
            }
        }
    
    }
    
    • 修改MVPBaseActivity继承BaseActivity
    四、Package(rxretrofit)
    • LoginService
    public interface LoginService {
    
    //    @GET("login/mlogin")
    //    Observable<String> getLoginResult(@Query("username") String username,
    //                                      @Query("password") String password);
    
        @FormUrlEncoded
        @POST("login/mlogin")
        Observable<String> getLoginResult(@Field("username") String username,
                                          @Field("password") String password);
    }
    
    • LoginApi
    public class LoginApi extends BaseApi {
    
        public static final String LOGIN_BASE_URL = "";
    
        private String username;
        private String password;
    
        public String getUsername() {
            return username;
        }
    
        public void setUsername(String username) {
            this.username = username;
        }
    
        public String getPassword() {
            return password;
        }
    
        public void setPassword(String password) {
            this.password = password;
        }
    
        public LoginApi() {
            setShowProgress(false);
            setCancel(false);
            setMothed("login/mlogin");
            setCache(false);
            // TODO 若BaseUrl非全局唯一的需在此处设置,全局唯一则在Application中设置BaseUrl
            setBaseUrl(LOGIN_BASE_URL);
        }
    
        @Override
        public Observable getObservable(Retrofit retrofit) {
            LoginService loginService = retrofit.create(LoginService.class);
            return loginService.getLoginResult(getUsername(), getPassword());
        }
    
    }
    
    五、修改
    • 修改LoginContract
    public class LoginContract {
    
        // TODO ========================================================================================
        interface View extends BaseView {
            void onNext(String result, String method);// 成功回调
            void onError(ApiException e);// 失败回调
            void showLoad();// 显示加载框
            void hideLoad();// 隐藏加载框
        }
    
        interface Presenter extends BasePresenter<View> {
            void startRequest(RxAppCompatActivity activity, BaseApi api);
        }
        // TODO ========================================================================================
    
    }
    
    • 修改LoginPresenter实现HttpOnNextListener
    public class LoginPresenter extends BasePresenterImpl<LoginContract.View> implements LoginContract.Presenter, HttpOnNextListener {
    
        // TODO ========================================================================================
        @Override
        public void startRequest(RxAppCompatActivity activity, BaseApi api) {
            mView.showLoad();
            HttpManager manager = new HttpManager(this, activity);
            manager.doHttpDeal(api);
        }
    
        @Override
        public void onNext(String result, String method) {
            mView.onNext(result, method);
            mView.hideLoad();
        }
    
        @Override
        public void onError(ApiException e) {
            mView.onError(e);
            mView.hideLoad();
        }
        // TODO ========================================================================================
    
    }
    
    • 修改LoginActivity
    public class LoginActivity extends MVPBaseActivity<LoginContract.View, LoginPresenter> implements LoginContract.View, View.OnClickListener {
    
        // TODO ========================================================================================
        private EditText etUsername;
        private EditText etPassword;
        private TextView tvLog;
    
        @Override
        protected void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_login);
            initView();
        }
    
        private void initView() {
            etUsername = (EditText) findViewById(R.id.activity_login_et_username);
            etPassword = (EditText) findViewById(R.id.activity_login_et_password);
            tvLog = (TextView) findViewById(R.id.activity_login_tv_log);
            findViewById(R.id.activity_login_btn_login).setOnClickListener(this);
        }
    
        @Override
        public void onClick(View view) {
            startRequest();
        }
    
        private void startRequest() {
            LoginApi api = new LoginApi();
            api.setUsername(etUsername.getText().toString().trim());
            api.setPassword(etPassword.getText().toString().trim());
            mPresenter.startRequest(this, api);
        }
    
        @Override
        public void onNext(String result, String method) {
            String succeed = "成功>>>>>>>>>>>>>>>>>>>>"
                    + "\n---------- result\n" + result
                    + "\n---------- method\n" + method
                    + "\n<<<<<<<<<<<<<<<<<<<<";
            tvLog.setText(succeed);
            Log.e("lstar", succeed);
        }
    
        @Override
        public void onError(ApiException e) {
            String failed = "失败>>>>>>>>>>>>>>>>>>>>"
                    + "\n---------- code\n" + e.getCode()
                    + "\n---------- message\n" + e.getMessage()
                    + "\n<<<<<<<<<<<<<<<<<<<<";
            tvLog.setText(failed);
            Log.e("lstar", failed);
        }
    
        @Override
        public void showLoad() {
            showLoading();
        }
    
        @Override
        public void hideLoad() {
            hideLoading();
        }
        // TODO ========================================================================================
    
    }
    

    如何设计一个靠谱的MVP架构
    Android MVP Plugin,一键完成MVP结构代码编写
    Android RxJava之网络处理
    Rx-Retrofit极简方式使用
    RxJava+Retrofit+OkHttp深入浅出-mvp(使用篇)
    RxJava+Retrofit+OkHttp深入浅出-mvp(使用篇)Demo

    相关文章

      网友评论

          本文标题:RxJava+Retrofit+OkHttp + MVP

          本文链接:https://www.haomeiwen.com/subject/rpmuyxtx.html