美文网首页
MVP抽取.md

MVP抽取.md

作者: 魔女小姐的猫 | 来源:发表于2020-06-22 21:46 被阅读0次

让子类的工作模式都按父类的执行 一个抽象类公开定义了执行它的方法的方式

网络抽取

HttpManager

public class HttpManger {
    private static volatile HttpManger httpManger;
    private final Retrofit.Builder builder;

    public static HttpManger getHttpManger() {
        if (httpManger == null) {
            synchronized (HttpManger.class) {
                if (httpManger == null) {
                    httpManger = new HttpManger();
                }
            }
        }
        return httpManger;
    }

    public HttpManger() {
        builder = new Retrofit.Builder()
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .client(getOkHttpClient());

    }

    private OkHttpClient getOkHttpClient() {
        OkHttpClient.Builder okBuilder = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)
                .retryOnConnectionFailure(true)
                .cache(new Cache(new File(UserApplication.getUserApplication().getCacheDir(), Cotasts.CACHE_NAME), 1024 * 1024 * 10))
                .addInterceptor(new CacheIntercetor())
                .addNetworkInterceptor(new CacheIntercetor());

        if (Cotasts.IS_DEBUG == true) {
            okBuilder.addInterceptor(new LoggingInterceptor());
        }

        return okBuilder.build();

    }

    class LoggingInterceptor implements Interceptor {

        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            long startTime = System.nanoTime();
            //          请求前
            Log.d("TAG", String.format("Sending request %s on %s%n%s",

                    request.url(), chain.connection(), request.headers()));

            //          请求中
            Response response = chain.proceed(request);

            //           请求后
            long endTime = System.nanoTime();
            Log.d("TAG", String.format("Received response for %s in %.1fms%n%s",
                    response.request().url(), (endTime - startTime) / 1e6d, response.headers()));
            return response;
        }
    }


    class CacheIntercetor implements Interceptor {

        @Override
        public Response intercept(Chain chain) throws IOException {
            //请求前
            Request request = chain.request();

            //判断如果无网时,设置缓存协议
            if (!isNetWorkAvaiable(UserApplication.getUserApplication())) {
                request = request.newBuilder().cacheControl(CacheControl.FORCE_CACHE).build();
            }

            //网络请求
            Response response = chain.proceed(request);

            //是否有网
            if (isNetWorkAvaiable(UserApplication.getUserApplication())) {
                int maxAge = 0;
                response = response.newBuilder().removeHeader("Pragma")
                        .addHeader("Cache-Control", "public ,max-age=" + maxAge)
                        .build();
                return response;
            } else {
                int maxStale = 60 * 60 * 24;
                response = response.newBuilder().removeHeader("Pragma")
                        .addHeader("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
                        .build();
                return response;
            }
        }
    }

    public boolean isNetWorkAvaiable(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = connectivityManager.getActiveNetworkInfo();
        if (info != null) {
            return info.isAvailable();
        }
        return false;
    }

    public <T> T getApiService(String baseUrl, Class<T> clazz) {
        return builder.baseUrl(baseUrl).build().create(clazz);
    }
}

  

RxUtil

/**
 * 抽取线程切换
 */
public class RxUtil {
    /**
     * <T, T> 转换前的对象类型 | 转换后的对象类型
     *
     * @param <T>
     * @return
     */
    public static <T> ObservableTransformer<T, T> rxObservableTransformer() {
        return new ObservableTransformer<T, T>() {
            @Override
            public ObservableSource<T> apply(Observable<T> upstream) {
                return upstream
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread());
            }
        };
    }

//背压
    public static  <T>FlowableTransformer<T,T> onFlowableTransformer(){
        return new FlowableTransformer<T, T>() {
            @Override
            public Publisher<T> apply(Flowable<T> upstream) {
                return upstream.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread());
            }
        };
    }

}

baseFlowable基类

package com.example.day7work.base;

import android.util.Log;

import io.reactivex.subscribers.ResourceSubscriber;

public abstract class BaseFlowable<T>  extends ResourceSubscriber<T> {
    @Override
    public void onNext(T t) {
        onSucess(t);
    }

    protected abstract void onSucess(T t);

    @Override
    public void onError(Throwable t) {
        onFail(t.getMessage());

                   /** //对异常进行分类,不同的异常提示用户不同的信息
                        if (e instanceof HttpException) {
                            //   HTTP错误
                            callBack.onFail("HTTP错误");
                        } else if (e instanceof ConnectException
                                || e instanceof UnknownHostException) {
                            //   连接错误
                            callBack.onFail("连接错误");
                        } else if (e instanceof InterruptedIOException) {
                            //  连接超时
                            callBack.onFail("连接超时");
                        } else if (e instanceof JsonParseException
                                || e instanceof JSONException
                                || e instanceof ParseException) {
                            //  解析错误
                            callBack.onFail("解析错误");
                        } else {
                            if (e != null) {
                                callBack.onFail(e.toString());
                            } else {
                                callBack.onFail("未知错误");
                            }
                        }*/

    }

    protected abstract void onFail(String message);

    @Override
    public void onComplete() {
        Log.i("tag", "完成");
    }
}

base基类

观察者抽取

/**
 * 封装观察者
 *
 * @param <T>
 */
public abstract class BaseObserver<T> implements Observer<T> {
    private Disposable mDisposable;
    private BaseModel mModel;

    public BaseObserver(BaseModel mModel) {
        this.mModel = mModel;
    }

    @Override
    public void onSubscribe(Disposable d) {
        mDisposable = d;
        mModel.addModel(mDisposable);
        Log.e("TAG", "onSubscribe: " + "订阅成功");
    }

    @Override
    public void onNext(T t) {
        onSuccess(t);
        //断开订阅
        mDisposable.dispose();
        mModel.compositeDisposable.remove(mDisposable);
    }

    @Override
    public void onError(Throwable e) {
        onFail("onError: " + e.getMessage());
    }

    @Override
    public void onComplete() {
        Log.e("TAG", "onComplete");
    }

    public abstract void onSuccess(T t);

    public abstract void onFail(String error);

}

BaseActivity

/**
 * 封装activity
 */
public abstract class BaseActivity<P extends BasePresenter, V extends BaseView> extends AppCompatActivity {
    protected P mPresenter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayoutId());
        ButterKnife.bind(this);
        //抽取MVP
        mPresenter = initMvpPresenter();
        if (mPresenter != null) {
            mPresenter.setmView(initMvpView());
        }

        initView();
        initData();
        initListener();
    }

    protected abstract V initMvpView();

    protected abstract P initMvpPresenter();

    private void initListener() {
    }

    private void initData() {
    }

    private void initView() {
    }

    protected abstract int getLayoutId();

    public void toast(String toastMsg){
        Toast.makeText(this, toastMsg, Toast.LENGTH_SHORT).show();
    }
}

BaseFragment

public abstract
class BaseFragment<P extends BasePresenter, V extends BaseView> extends Fragment {

    protected P mPresenter;
    private View view;
    private Unbinder bind;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(getLayoutId(), container, false);
        bind = ButterKnife.bind(this, view);

        mPresenter = initMvpPresenter();
        if (mPresenter != null) {
            mPresenter.setmView(initMvpView());
        }

        initView();
        initData();
        initListener();
        return view;
    }

    protected abstract V initMvpView();

    protected abstract P initMvpPresenter();

    private void initListener() {
    }

    private void initData() {
    }

    private void initView() {
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        bind.unbind();
    }

    protected abstract int getLayoutId();
}

BaseCallback

public interface BaseCallback<T> {
    void onSuccess(T t);

    void onFail(String error);
}

BaseView

public interface BaseView<T> {
    void onSuccess(T t);

    void onFail(String error);
}

BaseModel

public abstract class BaseModel {
    public CompositeDisposable compositeDisposable;

    public void onDestroy() {
        //切断所有的 disposable 对象
        if (compositeDisposable != null) {
            compositeDisposable.clear();
        }
    }

    public void addModel(Disposable disposable) {
        if (compositeDisposable == null) {
            compositeDisposable = new CompositeDisposable();
        }
        compositeDisposable.add(disposable);
    }
}

BasePresenter

/**
 * 有界泛型 mView
 * 封装presenter
 *
 * @param <V>
 */
public abstract class BasePresenter<V extends BaseView> {
    protected V mView;
    private ArrayList<BaseModel> models = new ArrayList<>();

    public void setmView(V mView) {
        this.mView = mView;
    }

    public BasePresenter() {
        initModel();
    }

    protected abstract void initModel();

    public void onDestroy() {
        //打断 p 层和 v层的联系
        mView = null;
        if (models.size() > 0) {
            //掐断网络请求
            for (BaseModel model : models) {
                model.onDestroy();
            }
            models.clear();
        }
    }

    public void addModel(BaseModel model) {
        models.add(model);
    }
}


使用

ImpLoginPresenter

public
class ImpLoginPresenter extends BasePresenter implements LoginPresenter, LoginCallback {

    private ImpLoginModel model;

    @Override
    public void login(String username, String password) {
        if (TextUtils.isEmpty(username)) {
            mView.onFail("姓名不能为空");
            return;
        }

        if (TextUtils.isEmpty(password)) {
            mView.onFail("密码不能为空");
            return;
        }

        model.login(username, password, this);
    }

    @Override
    protected void initModel() {
        model = new ImpLoginModel();
        addModel(model);
    }

    @Override
    public void onSuccess(LoginBean loginBean) {
        mView.onSuccess(loginBean);
    }

    @Override
    public void onFail(String error) {
        mView.onFail(error);
    }
}

ImpLoginModel

public class ImpLoginModel extends BaseModel implements LoginModel {

    @Override
    public void login(String username, String password, LoginCallback loginCallback) {
        HttpManager.getHttpManager()
                .getApiService(ApiService.baseLoginUrl, ApiService.class)//获取接口服务对象
                .login(username, password)
                .compose(RxUtil.rxObservableTransformer())//RxUtil 切换线程
                .subscribe(new BaseObserver<LoginBean>(this) {
                    @Override
                    public void onSuccess(LoginBean loginBean) {
                        int errorCode = loginBean.getErrorCode();
                        if (errorCode == 0) {
                            loginCallback.onSuccess(loginBean);
                        } else {
                            loginCallback.onFail(loginBean.getErrorMsg());
                        }
                    }

                    @Override
                    public void onFail(String error) {
                        loginCallback.onFail(error);
                    }
                });
    }
}

相关文章

  • MVP抽取.md

    让子类的工作模式都按父类的执行 一个抽象类公开定义了执行它的方法的方式 网络抽取 HttpManager RxUt...

  • MVP抽取

    为什么要抽取? 每一个页面都用到同样的内容,每次都写同样的代码,浪费;规定代码的编写规范;多人开发维护变得简单。 ...

  • Mvp抽取

    为什么要抽取? 每一个页面都用到同样的内容,每次都写同样的代码,浪费;规定代码的编写规范;多人开发维护变得简单。 ...

  • MVP抽取

    描述: 当我们的逻辑功能越来越多,每个功能点都要写一套MVP,是一件很繁琐的事情。因此我们要对MVP的进行封装和抽...

  • MVP抽取

    为什么要抽取? 每一个页面都用到同样的内容,每次都写同样的代码,浪费; 规定代码的编写规范; 多人开发维护变得简单...

  • MVP抽取

    一、抽取原因 每一个页面都用到同样的内容,每次都写同样的代码,浪费;规定代码的编写规范;多人开发维护变得简单。 二...

  • MVP 终极抽取(下)

    流程图: 通过MVP终极抽取(上)让我们可以知道Model 的抽取。那么开始view ,presenter 的抽取...

  • 自制MVP基类框架依赖库和工具类(自用)

    抽取 除了mvp层的抽取,还有对Activity、Adapter、Fragment的抽取 工具类 验证码工具类:C...

  • Mvp_抽取

    1.BaseActivity层 2.BaseCallBack层(与BaseView层相同) 3.Baseview层...

  • MVP终极抽取(上)

    流程图: 首先创建model 层 并且对他的请求参数,网络请求,数据参数,进行封装,这样可以减小相似代码。更简洁。...

网友评论

      本文标题:MVP抽取.md

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