android mvp rxjava rxlife retrofit 项目实践

所用到的jcenter 

compile 'com.trello.rxlifecycle2:rxlifecycle:2.2.1'
compile 'com.trello.rxlifecycle2:rxlifecycle-android:2.2.1'
compile 'com.trello.rxlifecycle2:rxlifecycle-components:2.2.1'
compile 'com.squareup.okhttp3:logging-interceptor:3.4.1'
compile 'com.squareup.retrofit2:adapter-rxjava2:2.4.0'
compile 'io.reactivex.rxjava2:rxjava:2.1.9'
compile 'io.reactivex.rxjava2:rxandroid:2.0.2'

先从 retrofit 开始封装起

public class RetrofitHelper {
    //设置开启body日志
    public static boolean OPEN_LOG = true;
    private static OkHttpClient client = new OkHttpClient();
    private static final int DEFAULT_TIME_OUT = 30;//超时时间 5s
    private static final int DEFAULT_READ_TIME_OUT = 30;

    public static RetrofitService resetRetrofit() {
                if (OPEN_LOG) {
                    HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
                    logging.setLevel(HttpLoggingInterceptor.Level.BODY);
                    client = new OkHttpClient.Builder().addInterceptor(logging).build();
                }
        OkHttpClient.Builder builder = client.newBuilder();
        builder.connectTimeout(DEFAULT_TIME_OUT, TimeUnit.SECONDS);//连接超时时间
        builder.writeTimeout(DEFAULT_READ_TIME_OUT, TimeUnit.SECONDS);//写操作 超时时间
        builder.readTimeout(DEFAULT_READ_TIME_OUT, TimeUnit.SECONDS);//读操作超时时间

        Retrofit mRetrofit = new Retrofit.Builder()
                .baseUrl(ApiConstanse.BASE_URL)
                .client(client)
                .addConverterFactory(FastJsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
        return mRetrofit.create(RetrofitService.class);
    }

    public static MultipartBody.Part getMultiPart(String fileKey, File file) {
        RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        Log.e("filename", file.getName());
        return MultipartBody.Part.createFormData(fileKey, file.getName(), requestFile);
    }
}

 因为用到了fastjson 下面是fastjson的factory封装

public class FastJsonConverterFactory extends Converter.Factory{

    public static FastJsonConverterFactory create() {
        return new FastJsonConverterFactory();
    }

    /**
     * 需要重写父类中responseBodyConverter,该方法用来转换服务器返回数据
     */
    @Override
    public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
        return new FastJsonResponseBodyConverter<>(type);
    }

    /**
     * 需要重写父类中responseBodyConverter,该方法用来转换发送给服务器的数据
     */
    @Override
    public Converter<?, RequestBody> requestBodyConverter(Type type, Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
        return new FastJsonRequestBodyConverter<>();
    }
}
public class FastJsonRequestBodyConverter<T> implements Converter<T, RequestBody> {
    private static final MediaType MEDIA_TYPE = MediaType.parse("application/json; charset=UTF-8");

    @Override
    public RequestBody convert(T value) throws IOException {
        return RequestBody.create(MEDIA_TYPE, JSON.toJSONBytes(value));
    }
}
public class FastJsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {
    private final Type type;

    public FastJsonResponseBodyConverter(Type type) {
        this.type = type;
    }

    /*
    * 转换方法
    */
    @Override
    public T convert(ResponseBody value) throws IOException {
        BufferedSource bufferedSource = Okio.buffer(value.source());
        String tempStr = bufferedSource.readUtf8();
        Logger.e("获取接口数据",tempStr);
        bufferedSource.close();
        return JSON.parseObject(tempStr, type);

    }
}
public class ObservableHelper {
    public static <T>Observable<T> getObservable(Observable<T> apiObservable, LifecycleTransformer<T> composer) {
        //showLog(request);
        Observable<T> observable;
        //随生命周期自动管理.eg:onCreate(start)->onStop(end)
        observable =apiObservable
                .compose(composer)//需要在这个位置添加
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());
        return observable;
    }
}

view:

public interface BaseView {

    /**
     * 显示加载中
     */
    public void showLoading();

    /**
     * 隐藏加载
     */
    public void hideLoading();

    /**
     * 数据获取失败
     */
    public void onError(String msg, int code);

    /**
     * 数据获取成功
     */
    public void onSuccess();

    /**
     * 管理rx 生命周期
     *
     * @param <T>
     * @return
     */
    public <T> LifecycleTransformer<T> bindAutoDispose();
}
Presenter:
public class BasePresenter <V extends BaseView> {
    public static final String TAG=BasePresenter.class.getName();
    private WeakReference<V>  mView;

    /**
     * 绑定view,一般在初始化中调用该方法
     *
     * @param view view
     */
    public void attachView(V view) {
        this.mView =new WeakReference<V>(view);

    }

    /**
     * 解除绑定view,一般在onDestroy中调用
     */
    public V getView(){
       return mView.get();
    }
    public void detachView() {
        this.mView.clear();
        this.mView = null;

    }

    /**
     * View是否绑定
     *
     * @return
     */
    public boolean isViewAttached() {
        return null!= mView&&mView.get()!=null;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值