|  |  | 
 |  |  | import android.util.Log; | 
 |  |  |  | 
 |  |  | import com.google.gson.Gson; | 
 |  |  | import com.runt.open.mvi.base.BaseActivity; | 
 |  |  | import com.runt.open.mvi.data.HttpApiResult; | 
 |  |  |  | 
 |  |  | import java.net.ConnectException; | 
 |  |  | 
 |  |  |  */ | 
 |  |  | public abstract class HttpObserver<RESULT> implements Observer<HttpApiResult<RESULT>> { | 
 |  |  |  | 
 |  |  |     BaseActivity activity; | 
 |  |  |  | 
 |  |  |     public HttpObserver() { | 
 |  |  |     } | 
 |  |  |  | 
 |  |  |     public HttpObserver(BaseActivity activity) { | 
 |  |  |         this.activity = activity; | 
 |  |  |     } | 
 |  |  |  | 
 |  |  |     final String TAG = "HttpObserver"; | 
 |  |  |     protected int observerStatus;//0 订阅  1 响应 2 请求错误  3 结束 | 
 |  |  |  | 
 |  |  |     @Override | 
 |  |  |     public void onSubscribe(Disposable d) { | 
 |  |  |         observerStatus = 0 ; | 
 |  |  |         Log.d(TAG,"onSubscribe "+hashCode()); | 
 |  |  |     } | 
 |  |  |  | 
 |  |  |     @Override | 
 |  |  |     public void onNext(HttpApiResult<RESULT> httpResult) { | 
 |  |  |         observerStatus = 1; | 
 |  |  |         Log.d(TAG,"onNext "+httpResult); | 
 |  |  |         if (httpResult != null && httpResult.code == 0) { | 
 |  |  |             onSuccess(httpResult.data); | 
 |  |  |             handleResult(httpResult.data); | 
 |  |  |         }else{ | 
 |  |  |             onFailed(httpResult);//接口返回错误 | 
 |  |  |         } | 
 |  |  | 
 |  |  |  | 
 |  |  |     @Override | 
 |  |  |     public void onError(Throwable e) { | 
 |  |  |         observerStatus = 2; | 
 |  |  |         Log.e(TAG,"onError "+e.getMessage()+" "+hashCode()); | 
 |  |  |         int code = 600; | 
 |  |  |         String msg = "网络请求失败,请检查网络或稍后重试"; | 
 |  |  | 
 |  |  |  | 
 |  |  |     @Override | 
 |  |  |     public void onComplete() { | 
 |  |  |         observerStatus = 3; | 
 |  |  |         Log.i(TAG,"onComplete "+hashCode()); | 
 |  |  |     } | 
 |  |  |  | 
 |  |  |     protected abstract void onSuccess(RESULT data); | 
 |  |  |     /** | 
 |  |  |      * 处理返回数据 | 
 |  |  |      * @param result | 
 |  |  |      */ | 
 |  |  |     public abstract void handleResult(RESULT result); | 
 |  |  |  | 
 |  |  |     protected void onFailed(HttpApiResult error){ | 
 |  |  |         Log.i(TAG,"onFailed "+activity); | 
 |  |  |         if(activity != null){ | 
 |  |  |             activity.showToast(error.msg); | 
 |  |  |         } | 
 |  |  |     } | 
 |  |  |     /** | 
 |  |  |      * 请求错误信息 | 
 |  |  |      */ | 
 |  |  |     public abstract void onFailed(HttpApiResult<RESULT> result); | 
 |  |  |  | 
 |  |  | } |