| | |
| | | |
| | | import android.util.Log; |
| | | |
| | | import androidx.lifecycle.MutableLiveData; |
| | | |
| | | import com.auto.lyric.data.BaseApiResult; |
| | | |
| | | import java.io.EOFException; |
| | | import java.lang.reflect.ParameterizedType; |
| | | import java.net.SocketTimeoutException; |
| | | |
| | |
| | | |
| | | final String TAG = "HttpObserver"; |
| | | |
| | | MutableLiveData<T> resultLive; |
| | | |
| | | public HttpObserver(MutableLiveData<T> resultLive) { |
| | | this.resultLive = resultLive; |
| | | } |
| | | |
| | | protected T value; |
| | | |
| | | @Override |
| | | public void onNext(T value) { |
| | | resultLive.setValue(value); |
| | | this.value = value; |
| | | } |
| | | |
| | | /** |
| | | * 错误处理 |
| | | * @param throwable |
| | | */ |
| | | @Override |
| | | public void onError(Throwable throwable) { |
| | | Log.i("subscribe","onError"); |
| | | |
| | | Log.e("subscribe","onError "+throwable); |
| | | T t = null; |
| | | try { |
| | | Log.e(TAG,this.getClass().getSimpleName()+" "+throwable.getMessage()); |
| | | Class<T> entityClass = (Class<T>) ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[0]; |
| | | T t = entityClass.newInstance();//实例化一个泛型 |
| | | t.code = 410; |
| | | t = entityClass.newInstance();//实例化一个泛型 |
| | | t.result = "410"; |
| | | if( throwable instanceof SocketTimeoutException){ |
| | | t.msg = "服务请求超时,请稍候再试";//设置错误信息 |
| | | t.reason = "服务请求超时,请稍候再试";//设置错误信息 |
| | | }else if(throwable instanceof EOFException){ |
| | | t.reason = "服务未反馈任何内容";//设置错误信息 |
| | | }else{ |
| | | t.msg = "网络连接不畅,请检查您的网络设置";//设置错误信息 |
| | | t.reason = "网络连接不畅,请检查您的网络设置";//设置错误信息 |
| | | } |
| | | resultLive.setValue(t); |
| | | } catch (ClassCastException e) { |
| | | e.printStackTrace(); |
| | | T t = (T) new BaseApiResult<String>(); |
| | | t.code = 409; |
| | | t.msg = "实例化对象未指定泛型实体类"; |
| | | resultLive.setValue(t); |
| | | t = (T) new BaseApiResult(); |
| | | t.result = "409"; |
| | | t.reason = "实例化对象未指定泛型实体类"; |
| | | } catch (Exception e) { |
| | | e.printStackTrace(); |
| | | T t = (T) new BaseApiResult<String>(); |
| | | t.code = 409; |
| | | t.msg = e.getMessage(); |
| | | resultLive.setValue(t); |
| | | t.result = "409"; |
| | | t.reason = e.getMessage(); |
| | | } |
| | | onError(t); |
| | | } |
| | | |
| | | @Override |
| | | public void onComplete() { |
| | | if(value.result.equals("success")){ |
| | | //返回成功 |
| | | onComplete(value); |
| | | }else{ |
| | | //返回失败 |
| | | onError(value); |
| | | } |
| | | Log.i("subscribe","onComplete"); |
| | | } |
| | | |
| | | /** |
| | | * 接口返回成功 |
| | | * @param result |
| | | */ |
| | | public abstract void onError(T result) ; |
| | | |
| | | /** |
| | | * 接口返回失败 |
| | | * @param error |
| | | */ |
| | | public abstract void onComplete(T error) ; |
| | | } |