现在,我已经解决了以下问题:
data class RequestResult<T>(
val data: T,
val code: Int
)
fun <T> transformResponse(response: Response<T>): Single<RequestResult<T>> {
if (response.isSuccessful) {
return Single.just(RequestResult(response.body()!!, response.code()))
} else {
throw HttpException(response)
}
}
fun <T> transformEmptyResponse(response: Response<T>): Completable {
if (response.isSuccessful) {
return Completable.complete()
} else {
throw HttpException(response)
}
}
fun linkDevice(): Single<UserDevice> {
val deviceInfo = deviceUtil.getDeviceInfo()
return devicesService
.linkDevice(deviceInfo)
.flatMap { transformResponse(it) }
.flatMap { requestResult ->
requestResult.data.let { userDevice ->
userPreferences.setDeviceId(userDevice.id)
when (requestResult.code) {
200 -> {
// TODO: Analytics
}
201 -> {
// TODO: Analytics
}
}
Single.just(userDevice)
}
}
.onErrorResumeNext { e ->
val transformedException = transformRequestException(e) { httpException ->
return@transformRequestException when (httpException.code()) {
409 -> DeviceAlreadyLinkedException()
else -> null
}
}
Single.error(transformedException)
}
}
看起来像黑客,但我没有找到更好的解决方案,它的工作。