返回LiveData观察结果作为Authenticator类的Request

时间:2019-02-12 08:57:08

标签: android kotlin android-livedata

我正在研究Authenticator类,该类将刷新令牌和令牌保存到数据库或从数据库中加载。

我的Dao返回LiveData>,我需要查询它以找到具有特定用户名的用户,并通过Dao的update命令更新令牌和刷新令牌。

class TokenAuthenticator(private val userName :String, private val activity : MainActivity , private val service : AuthenticateService) : Authenticator {

lateinit var  userForSave: User
private lateinit var userViewModel: UserViewModel
override fun authenticate(route: Route?, response: Response): Request? {
    userViewModel = ViewModelProviders.of(activity).get(UserViewModel::class.java)
    if(responseCount(response) >= 2) {
        return null
    }
     userViewModel.allUsers.observe(activity, Observer { result ->
        userForSave = result!!.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
        userViewModel.update(userForSave!!)
        return response.request()
            .newBuilder()
            .header("Authorization", "Bearer ${userForSave!!.token}")
            .build()
    }
    return null
}
private fun responseCount(response: Response) : Int {
    var count = 1
    var res = response.priorResponse()
    while(res != null) {
        count++
        res = res.priorResponse()
    }
    return count
}
}

在调用新的刷新令牌之前,我需要获得找到的用户。换句话说,我需要类似“ Then()”的方法来确保userForSave具有数据。 此外,有没有使用ViewModel来获取数据的方法?只是使用Dao

0 个答案:

没有答案