package cn.flightfeather.thirdappmodule.common.net
|
|
import android.accounts.NetworkErrorException
|
import cn.flightfeather.thirdappmodule.model.bean.BaseResponse
|
import io.reactivex.Observer
|
import io.reactivex.disposables.Disposable
|
import retrofit2.Response
|
import java.net.ConnectException
|
import java.net.UnknownHostException
|
import java.util.concurrent.TimeoutException
|
|
/**
|
* @author riku
|
* Date: 2019/4/24
|
* RxJava2 网络请求返回处理
|
*/
|
abstract class ResultObserver<T>:Observer<Response<T>> {
|
|
override fun onSubscribe(d: Disposable) {
|
if (!d.isDisposed) {
|
onRequestStart()
|
}
|
}
|
|
override fun onNext(response: Response<T>) {
|
getPageInfo(response)
|
onRequestEnd()
|
if (response.isSuccessful) {
|
try {
|
onSuccess(response.body())
|
} catch (e: Exception) {
|
e.printStackTrace()
|
}
|
|
} else {
|
try {
|
onInnerCodeError(response.code(), response.message())
|
onCodeError(response.code(), response.message())
|
onFailure(Throwable(), false)
|
} catch (e: Exception) {
|
e.printStackTrace()
|
}
|
}
|
}
|
|
override fun onError(e: Throwable) {
|
onRequestEnd()
|
try {
|
if (e is ConnectException
|
|| e is TimeoutException
|
|| e is NetworkErrorException
|
|| e is UnknownHostException
|
) {
|
onFailure(e, true)
|
} else {
|
onFailure(e, false)
|
}
|
} catch (e1: Exception) {
|
e1.printStackTrace()
|
}
|
}
|
|
override fun onComplete() = Unit
|
|
|
private fun getPageInfo(response: Response<T>) {
|
var currentPage = -1
|
var totalPage = -1
|
try {
|
val body = response.body()
|
if (body is BaseResponse<*>) {
|
currentPage = body.head?.page ?: -1
|
totalPage = body.head?.totalPage ?: -1
|
}
|
} catch (e: Exception) {
|
e.printStackTrace()
|
}
|
onPage(currentPage, totalPage)
|
}
|
|
|
/***********自定义回调方法***********/
|
/**
|
* 请求开始
|
*/
|
open fun onRequestStart() = Unit
|
|
/**
|
* 获取到分页信息
|
*/
|
open fun onPage(current: Int, total: Int) = Unit
|
|
/**
|
* 请求结束
|
*/
|
open fun onRequestEnd() = Unit
|
|
/**
|
* 网络请求返回成功,但code错误
|
*/
|
open fun onInnerCodeError(code: Int, message: String) = Unit
|
|
/**
|
* 提供网络请求返回错误代码时的自定义处理方法
|
*/
|
open fun onCodeError(code: Int, message: String) = Unit
|
|
/**
|
* 请求成功
|
*/
|
@Throws(Exception::class)
|
abstract fun onSuccess(result: T?)
|
|
/**
|
* 请求失败
|
*/
|
@Throws(java.lang.Exception::class)
|
abstract fun onFailure(e: Throwable, isNetWorkError: Boolean)
|
|
}
|