Runt
2022-08-17 2a320dc04d6deb22116ebfd302d6f898a15f23af
app/src/main/java/com/runt/open/mvvm/retrofit/observable/HttpObserver.java
@@ -1,96 +1,83 @@
package com.runt.open.mvvm.retrofit.observable;
import android.accounts.NetworkErrorException;
import android.util.Log;
import com.google.gson.Gson;
import com.runt.open.mvvm.base.activities.BaseActivity;
import com.runt.open.mvvm.data.HttpApiResult;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import retrofit2.adapter.rxjava2.HttpException;
import androidx.annotation.NonNull;
import androidx.lifecycle.MutableLiveData;
import com.runt.open.mvvm.data.BaseApiResult;
import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import io.reactivex.SingleObserver;
import io.reactivex.observers.DisposableObserver;
import retrofit2.Response;
import java.net.UnknownHostException;
import java.util.concurrent.TimeoutException;
import java.util.regex.Pattern;
/**
 * 网络请求观察
 * Created by Administrator on 2021/11/11 0011.
 */
public abstract class HttpObserver<M extends BaseApiResult> extends DisposableObserver<Response<M>> implements SingleObserver<Response<M>> {
public abstract class HttpObserver<RESULT> implements Observer<HttpApiResult<RESULT>> {
    BaseActivity activity;
    public HttpObserver() {
    }
    public HttpObserver(BaseActivity activity) {
        this.activity = activity;
    }
    final String TAG = "HttpObserver";
    MutableLiveData<M> resultLive;
    public HttpObserver(MutableLiveData<M> resultLive) {
        this.resultLive = resultLive;
    }
    @Override
    public void onNext(Response<M> response) {
        onExcuted(response);
    public void onSubscribe(Disposable d) {
        Log.d(TAG,"onSubscribe "+hashCode());
    }
    @Override
    public void onError(Throwable throwable) {
        Log.i("subscribe","onError");
        try {
            Log.e(TAG,this.getClass().getSimpleName()+" mes:"+throwable.getMessage());
            Class<M> entityClass = (Class<M>) ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[0];
            M t = entityClass.newInstance();//实例化一个泛型
            t.code = 410;
            if( throwable instanceof SocketTimeoutException){
                t.msg = "服务请求超时,请稍候再试";//设置错误信息
            }else  if( throwable instanceof NetworkErrorException){
                t.msg = "网络连接不畅,请检查您的网络设置";//设置错误信息
            }else{
                t.msg = throwable.getMessage();//设置错误信息
            }
            resultLive.setValue(t);
        } catch (ClassCastException e) {
            e.printStackTrace();
            M t = (M) new BaseApiResult<String>();
            t.code = 409;
            t.msg = "实例化对象未指定泛型实体类";
            resultLive.setValue(t);
        } catch (Exception e) {
            e.printStackTrace();
            M t = (M) new BaseApiResult<String>();
            t.code = 409;
            t.msg = e.getMessage();
            resultLive.setValue(t);
        }
    }
    @Override
    public void onSuccess(Response<M> response) {
        onExcuted(response);
    }
    private void onExcuted(@NonNull Response<M> response){
        if(response.body() != null){
            resultLive.setValue(response.body());
    public void onNext(HttpApiResult<RESULT> httpResult) {
        Log.d(TAG,"onNext "+httpResult);
        if (httpResult != null && httpResult.code == 0) {
            onSuccess(httpResult.data);
        }else{
            try {
                String error = response.errorBody().string();
                Log.i("subscribe","onExcuted "+error);
                onError(new Throwable(error));
            } catch (IOException e) {
                e.printStackTrace();
            }
            onFailed(httpResult);//接口返回错误
        }
    }
    @Override
    public void onError(Throwable e) {
        Log.e(TAG,"onError "+e.getMessage()+" "+hashCode());
        int code = 600;
        String msg = "网络请求失败,请检查网络或稍后重试";
        if( e instanceof ConnectException || e instanceof TimeoutException
                || e instanceof SocketTimeoutException || e instanceof UnknownHostException){
            code = 601;
            msg = "网络请求失败,请检查网络或稍后重试";
        }else if( e instanceof HttpException){
            String regEx = "[^0-9]";
            Log.i(TAG,"code:"+ Pattern.compile(regEx).matcher(e.getMessage()).replaceAll(""));
            String error = Pattern.compile(regEx).matcher(e.getMessage()).replaceAll("");
            code = error.length()>0?Integer.parseInt(error):500;
            msg = error.length()>0?"服务器请求失败":"登录信息验证失败";
        }
        HttpApiResult httpResult = new Gson().fromJson("{'code':"+code+",'msg':'"+msg+"'}", HttpApiResult.class);
        onFailed(httpResult);
    }
    @Override
    public void onComplete() {
        Log.i("subscribe","onComplete");
        Log.i(TAG,"onComplete "+hashCode());
    }
    protected abstract void onSuccess(RESULT data);
    protected void onFailed(HttpApiResult error){
        Log.i(TAG,"onFailed "+activity);
        if(activity != null){
            activity.showToast(error.msg);
        }
    }
}