[英]Retrofit - OkHttp Authenticator- How to make other api calls pause till the authenticator completes execution
我在使用 viewmodel scope 启动的屏幕中有多个 api 调用,就像在 viewmodel 中这样
viewModelScope.launch {
apiCallOne()
}
viewModelScope.launch {
apiCallTwo()
}
viewModelScope.launch {
apiCallThree()
}
我的身份验证者是
override fun authenticate(route: Route?, response: Response): Request? {
return if (response.retryCount < 1) {
val token = refreshToken()
if (token != null)
response.request.newBuilder().header("Authorization", "Bearer $token")
.build()
else
null
} else {
navigateToOnboardingActivity()
null
}
}
It is working fine but when 3 api calls are launched parallely, the session is getting refreshed 3 times, how can i make it work like if apicallOne() get 401, it will got to autnenticator and call refresh token api, in this time apicallTwo () 和 apicallThree() 应该在第一个authenticaor 获得成功响应后暂停和恢复。
请注意,我不能像这样在单次启动中调用所有 API
viewModelScope.launch{
apiCallOne()
apiCallTwo()
apiCallThree()
}
你可以像这个例子一样使用:
viewModelScope.launch{
val result1 = async{apiCallOne()}.await()
if (result1.code() != 401) {
apiCallTwo()
apiCallThree()
}
}
或这个:
viewModelScope.launch{
val result1 = withContext(Dispatchers.Default) {apiCallOne()}
if (result1.code() != 401) {
apiCallTwo()
apiCallThree()
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.