package com.auto.lyric.retrofit.observable;
|
|
import android.util.Log;
|
|
import com.auto.lyric.data.BaseApiResult;
|
|
import java.io.EOFException;
|
import java.lang.reflect.ParameterizedType;
|
import java.net.SocketTimeoutException;
|
|
import io.reactivex.observers.DisposableObserver;
|
|
/**
|
* 网络请求观察
|
* Created by Administrator on 2021/11/11 0011.
|
*/
|
public abstract class HttpObserver<T extends BaseApiResult> extends DisposableObserver<T>{
|
|
final String TAG = "HttpObserver";
|
|
protected T value;
|
|
@Override
|
public void onNext(T value) {
|
this.value = value;
|
}
|
|
/**
|
* 错误处理
|
* @param throwable
|
*/
|
@Override
|
public void onError(Throwable throwable) {
|
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 = entityClass.newInstance();//实例化一个泛型
|
t.result = "410";
|
if( throwable instanceof SocketTimeoutException){
|
t.reason = "服务请求超时,请稍候再试";//设置错误信息
|
}else if(throwable instanceof EOFException){
|
t.reason = "服务未反馈任何内容";//设置错误信息
|
}else{
|
t.reason = "网络连接不畅,请检查您的网络设置";//设置错误信息
|
}
|
} catch (ClassCastException e) {
|
e.printStackTrace();
|
t = (T) new BaseApiResult();
|
t.result = "409";
|
t.reason = "实例化对象未指定泛型实体类";
|
} catch (Exception e) {
|
e.printStackTrace();
|
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) ;
|
}
|