我需要在观察方法完成后立即运行方法,但是我不知道如何操作。这是我的代码如下:
class TokenAuthenticator(private val userName :String, private val userDao: UserDao, private val service : AuthenticateService) : Authenticator {
override fun authenticate(route: Route?, response: Response): Request? {
// userViewModel = ViewModelProviders.of(activity).get(UserViewModel::class.java)
var userForSave: User? = null
if(responseCount(response) >= 2) {
return null
}
userDao.getAll().observe(this, Observer {users ->
users?.let{
userForSave = users.find{x:User -> x.userName == userName}!!
val tokenDto: TokenDto = TokenDto(token = userForSave!!.token, refreshToken = userForSave!!.refreshToken)
val refreshTokenCall = service.refreshToken(tokenDto)
val refreshResponse = refreshTokenCall.execute()
if(refreshResponse.isSuccessful) {
userForSave!!.token = refreshResponse!!.body()!!.token
userForSave!!.refreshToken = refreshResponse!!.body()!!.refreshToken
userDao.update(userForSave!!)
// return response.request()
// .newBuilder()
// .header("Authorization", "Bearer ${userForSave!!.token}")
// .build()
}
}
}) // need a method here like "Then()" to create request object
return null
}
private fun responseCount(response: Response) : Int {
var count = 1
var res = response.priorResponse()
while(res != null) {
count++
res = res.priorResponse()
}
return count
}
}
当前代码在创建请求之前返回null。而且我也不能使用return