顾名思义,我目前正在使用具有异步回调方法的API。我希望能够在继续其余代码之前等待结果(如果可行的话,使现有的异步调用有些同步)。协程可能吗?这就是我的代码现在的样子,但是该请求仍被多次调用(我是协程新手)。
class TokenAuthenticator @Inject constructor(val prefs: AppPrefs) : Authenticator {
override fun authenticate(route: Route?, response: Response): Request? {
if (response.code() == ApiErrorCode.UNAUTHORIZED) {
Timber.w("Unauthorized. Refreshing token...")
val token: String? = runBlocking(Dispatchers.Main) { refreshToken() }
token?.let {
return response
.request()
.newBuilder()
.header("Authorization", "Bearer $token")
.build()
}
}
when (response.code()) {
ApiErrorCode.UNAUTHORIZED -> Timber.w("Tried to refresh token. Failed?")
else -> Timber.d("NOT refreshing token, response code was: ${response.code()}")
}
return response.request()
}
private suspend fun refreshToken() = suspendCoroutine<String?> {
SomeApi.getValidAccessToken(object : TokenCallback {
override fun onSuccess(accessToken: String?) {
Timber.d("Token successfully retrieved. Storing to prefs...")
prefs.userAuthToken = accessToken
it.resume(accessToken)
}
override fun onError(errorData: Any?) {
Timber.e("Error retrieving token")
it.resume(null)
}
})
}
}