我最近将Retrofit更新为2.7.0
,将OKHttp更新为3.14.4
,以利用Retrofit接口上的暂停乐趣。
除此之外,我还试图为刷新令牌逻辑实现Authenticator。
这是改造界面
interface OfficeApi {
@Authenticated
@POST
suspend fun getCharacter(): Response<CharacterResponse>
}
这是我的身份验证器
class CharacterAuthenticator : Authenticator {
override fun authenticate(
route: Route?,
response: Response
): Request? {
if (responseCount(response) >= 2) return null
return response.request()
.newBuilder()
.removeHeader("Authorization")
.addHeader("Authorization", "Bearer $newToken")
.build()
return null
}
private fun responseCount(response: Response?): Int {
var result = 1
while (response?.priorResponse() != null) result++
return result
}
}
这是改装乐趣
override suspend fun getCharacter() = safeApiCall(moshiConverter) {
myApi.getCharacter()
}
这是
safeApiCall
:suspend fun <T> safeApiCall(
moshiConverter: MoshiConverter,
apiCall: suspend () -> Response<T>
): Result<T?, ResultError.NetworkError> {
return try {
val response = apiCall()
if (response.isSuccessful) Result.Success(response.body())
else {
val errorBody = response.errorBody()
val errorBodyResponse = if (errorBody != null) {
moshiConverter.fromJsonObject(errorBody.string(), ErrorBodyResponse::class.java)
} else null
Result.Error(
ResultError.NetworkError(
httpCode = response.code(),
httpMessage = response.message(),
serverCode = errorBodyResponse?.code,
serverMessage = errorBodyResponse?.message
)
)
}
} catch (exception: Exception) {
Result.Error(ResultError.NetworkError(-1, exception.message))
}
}
身份验证器工作正常,尝试刷新令牌两次,然后放弃。问题是:当放弃(返回null)时,翻新(
safeApiCall
函数)的执行不会继续。通话是否成功,我没有任何反馈。使用Authenticator和Coroutines
suspend fun
有什么问题吗? 最佳答案
这不是一个无限循环吗?
while (response?.priorResponse() != null)
不是吗
var curResponse: Response? = response
while (curResponse?.priorResponse() != null) {
result++
curResponse = curResponse.priorResponse()
}