欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

MVP框架使用步骤

程序员文章站 2022-03-19 16:09:37
1、封装API(我这里只封装了两个方法)public interface IApi { //图片上传请求 @Multipart @POST Observable postimagemore(@Url String url, @QueryMap Map map, @Part List requestBody); //常用 登录或上传请求...

1、封装API(我这里只封装了两个方法)

public interface IApi {
    //图片上传请求
    @Multipart
    @POST
    Observable<RequestBody> postimagemore(@Url String url, @QueryMap Map<String, Object> map, @Part List<MultipartBody.Part> requestBody);
    //常用 登录或上传请求
    @POST
    Observable<ResponseBody> postInfo(@Url String path, @QueryMap Map<String, Object> map);
}

2、网络工具类

public class NetUtils {
    //私有化api接口
    private IApi iApi;
    //MMKV 存储  也可以使用sp存储
    MMKV mmkv= MMKV.defaultMMKV();
    //判断网络
    public static boolean isNetWork(Context context){
        ConnectivityManager manager= (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo=manager.getActiveNetworkInfo();
        if (networkInfo!=null&&networkInfo.isConnected()){
            return  true;
        }
        return false;
    }
    //创建 NetUtils 的一个对象
    private static final class Holder{
        private static NetUtils netUtils=new NetUtils();
    }
    //获取唯一可用的对象
    public static NetUtils getInstance(){
        return Holder.netUtils;
    }
    //单例
    private NetUtils(){
        //网络拦截器
        HttpLoggingInterceptor interceptor=new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient okHttpClient=new OkHttpClient.Builder()
                .readTimeout(5, TimeUnit.SECONDS)
                .connectTimeout(5, TimeUnit.SECONDS)
                .addInterceptor(interceptor)//添加拦截器
                .addInterceptor(new Interceptor() {
                    @Override
                    public Response intercept(Interceptor.Chain chain) throws IOException {
                        Request.Builder builder=chain.request().newBuilder();
                        int userId=mmkv.decodeInt("userId");
                        String sessionId=mmkv.decodeString("sessionId");
                        Log.e("userId",""+userId);
                        Log.e("sessionId",""+sessionId);
                        //入头参
                        if (sessionId!=null&&userId!=0){
                            builder.addHeader("sessionId",sessionId);
                            builder.addHeader("userId",userId+"");

                        }
                        builder.addHeader("ak","0110010010000");
                        return chain.proceed(builder.build());
                    }
                }).build();
        //创建Retrofit实例
        Retrofit retrofit=new Retrofit.Builder()
                .baseUrl(IMyUrls.BaseUrl_OuterNet)
                .addConverterFactory(GsonConverterFactory.create())//设置数据解析器
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())//使Retrofit支持Rxjava使用
                .client(okHttpClient)//添加OkHttpClient
                .build();
        //对外提供接口
        iApi=retrofit.create(IApi.class);
    }
    //接口回调
    public interface NetCallback<T>{
        void onSuccess(T t);
        void onError(String error);
    }
    //登录注册
    public void postlr(String url, Map<String,Object> map, final Class cls,
                       final NetCallback callback) {
        iApi.postInfo(url,map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResponseBody>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(ResponseBody responseBody) {
                        Gson gson=new Gson();
                        try {
                            Object object=gson.fromJson(responseBody.string(),cls);
                            callback.onSuccess(object);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(Throwable e
                    ) {
                        callback.onError(e.getMessage());
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }
    public void postFile(String url, Map<String,Object> map, List<MultipartBody.Part> requestBody, Class cls, NetCallback callback){
        iApi.postimagemore(url,map,requestBody)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<RequestBody>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(RequestBody requestBody) {
                        callback.onSuccess(requestBody);
                    }

                    @Override
                    public void onError(Throwable e) {
                        callback.onError(e.getMessage());
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }
}

3、契约

public interface IContract {
    //数据
    interface IModel{
        //登录注册
        void postLR(String url, Map<String,Object> map, Class cla, NetUtils.NetCallback callback);
        void postFile(String url, Map<String, Object> map, List<MultipartBody.Part> requestBody, Class cls, NetUtils.NetCallback callback);
    }
    //显示
    interface IView<T>{
        void onSuccess(T t);
        void onError(String error);
    }
    //逻辑
    interface IPresenter{
        //登录注册
        void ppostLR(String url, Map<String,Object> map, Class cla);
        void StartPostFile(String url, Map<String, Object> map, List<MultipartBody.Part> requestBody, Class cls);
    }
}

4、唯一的model层

public class ModelImpl implements IContract.IModel {
    @Override
    public void postLR(String url, Map<String, Object> map, Class cla, final NetUtils.NetCallback callback) {
        NetUtils.getInstance().postlr(url, map, cla, new NetUtils.NetCallback() {
            @Override
            public void onSuccess(Object o) {
                callback.onSuccess(o);
            }

            @Override
            public void onError(String error) {
                callback.onError(error);
            }
        });
    }

    @Override
    public void postFile(String url, Map<String, Object> map, List<MultipartBody.Part> requestBody, Class cls, NetUtils.NetCallback callback) {
        NetUtils.getInstance().postFile(url, map, requestBody, cls, new NetUtils.NetCallback() {
            @Override
            public void onSuccess(Object o) {
                callback.onSuccess(o);
            }

            @Override
            public void onError(String error) {
                callback.onError(error);
            }
        });
    }
}

5、presenter基类

public abstract class BasePresenter<V extends IContract.IView>implements IContract.IPresenter {
    private WeakReference<V> mWeak;
    private ModelImpl model;

    public BasePresenter(){
        model=new ModelImpl();
    }
    //绑定
    public void OnAttachView(V v){
        mWeak=new WeakReference<>(v);
    }
    //解绑
    public void OnDetachView(){
        if (mWeak!=null&&mWeak.get()!=null){
            mWeak.clear();
        }
    }
    //给子类提供view层方法
    public V getView(){
        return mWeak.get();
    }
    //给子类提供model层方法
    public ModelImpl getModel(){
        return model;
    }
}

6、唯一的presenter层

public class PresenterImpl extends BasePresenter {
    @Override
    public void ppostLR(String url, Map<String, Object> map, Class cla) {
        getModel().postLR(url, map, cla, new NetUtils.NetCallback() {
            @Override
            public void onSuccess(Object o) {
                getView().onSuccess(o);
            }

            @Override
            public void onError(String error) {
                getView().onError(error);
            }
        });
    }

    @Override
    public void StartPostFile(String url, Map<String, Object> map, List<MultipartBody.Part> requestBody, Class cls) {
        getModel().postFile(url, map, requestBody, cls, new NetUtils.NetCallback() {
            @Override
            public void onSuccess(Object o) {
                getView().onSuccess(o);
            }

            @Override
            public void onError(String error) {
                getView().onError(error);
            }
        });
    }
}

7、activity基类(fragment基类也差不多一样封装)

public abstract class BaseActivity<P extends BasePresenter<IContract.IView>> extends AppCompatActivity implements IContract.IView {
    public  P presenter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayout());
        ButterKnife.bind(this);
        presenter=initPresenter();
        presenter.OnAttachView(this);
        initData();

    }
    protected abstract P initPresenter();

    protected abstract void initData();

    protected abstract int getLayout();

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (presenter!=null){
            presenter.OnDetachView();
            presenter=null;
        }
    }
}

以上就完成了MVP的架构
此博客为个人记录使用,每天进步一点点~

本文地址:https://blog.csdn.net/weixin_51029424/article/details/110467455

相关标签: mvp