我最近更新了 Retrofit to2.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))
}
}
Authenticator 工作正常,尝试刷新令牌两次然后放弃。问题是:当它放弃时(返回null),retrofit(safeApiCall
函数)的执行不会继续。如果通话成功与否,我没有任何反馈。
使用 Authenticator 和 Coroutines 有什么问题suspend fun
吗?