具体使用见https://github.com/caiyoufei/ABase
1.ParameterizedType
import cc.ab.base.net.http.response.BaseResponse;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import org.jetbrains.annotations.NotNull;
public class BaseParameterizedTypeImpl implements ParameterizedType {
private final Class raw;
private final Type[] args;
private BaseParameterizedTypeImpl(Class raw, Type[] args) {
this.raw = raw;
this.args = args != null ? args : new Type[0];
}
public static Type typeOne(Class<?> clazz) {
return new BaseParameterizedTypeImpl(BaseResponse.class, new Class[] { clazz });
}
public static Type typeList(Class<?> clazz) {
// 生成List<T> 中的 List<T>
Type listType = new BaseParameterizedTypeImpl(List.class, new Class[] { clazz });
// 根据List<T>生成完整的Response<List<T>>
return new BaseParameterizedTypeImpl(BaseResponse.class, new Type[] { listType });
}
@NotNull @Override
public Type[] getActualTypeArguments() {
return args;
}
@NotNull @Override
public Type getRawType() {
return raw;
}
@Override
public Type getOwnerType() {
return null;
}
}
2.BaseResponse
data class BaseResponse<out T>(
val errorCode: Int = -1,//正常接口使用的状态码
var errorMsg: String? = null,//code异常对应的信息提示
val data: T? = null//正常返回的数据信息
)
3.真正转换
private inline fun <reified T> flatMapSingle(
result: Result<String, FuelError>
): Single<BaseResponse<T>> {
return if (result.component2() == null) {
Single.just(
converWanData(result.component1(), BaseParameterizedTypeImpl.typeOne(T::class.java))
)
} else {
Single.error(converFuelError(result.component2()))
}
}
private inline fun <reified T> flatMapSingleList(
result: Result<String, FuelError>
): Single<BaseResponse<MutableList<T>>> {
return if (result.component2() == null) {
Single.just(
converWanData(result.component1(), BaseParameterizedTypeImpl.typeList(T::class.java))
)
} else {
Single.error(converFuelError(result.component2()))
}
}
//数据转换(可能抛出异常)
@Throws
private fun <T> converWanData(
response: String?,
type: Type
): BaseResponse<T> {
if (response.isNullOrBlank()) throw converDataError()
try {
val result: BaseResponse<T> = GsonUtils.fromJson(response, type)
if (globalErrorCode.contains(result.errorCode)) {
result.errorMsg = null
dealGlobalErrorCode(result.errorCode)
}
return result
} catch (e: Exception) {
e.printStackTrace()
}
throw converDataError()
}
//统一处理
private fun dealGlobalErrorCode(errorCode: Int) {
val activity = ActivityUtils.getTopActivity()
activity?.let { ac ->
when (errorCode) {
//未登录
ErrorCode.NO_LOGIN -> {
ac.runOnUiThread {
ac.toast(R.string.need_login)
LoginActivity.startActivity(ac)
}
}
else -> {
}
}
}
}
异常处理
网友评论