gpt4 book ai didi

android - 如何在 token 验证器和注销用户中显示错误消息

转载 作者:行者123 更新时间:2023-12-05 05:56:30 25 4
gpt4 key购买 nike

我想刷新 token 并再次发送请求。如果成功我可以提出请求没有问题但是如果刷新 token 响应失败我想显示错误消息并将用户转发到登录屏幕。我在 TokenAuthenticator 类中也没有上下文,这是不可能的,因为它在我的 Hilt NetworkModule 中提供。

我尝试在 Session 中创建一个 MutableLiveData,并在下面的类中创建一个 postvalue true,但是当我在 BaseActivity 中观察它时,它会进入无限循环并在一次 postValue 之后每次触发。

我该如何解决这个问题?

class TokenAuthenticator(
val preferenceHelperImp: PreferenceHelperImp,
private val tokenApi: RefreshTokenApi,
) : Authenticator{

override fun authenticate(route: Route?, response: Response): Request? {
GlobalScope.launch {
getUpdatedRefreshToken(RefreshTokenRequest(preferenceHelperImp.getRefreshToken())
).collect {
when (it) {
is State.Success -> {
preferenceHelperImp.setCurrentUserLoggedInMode(Constants.App.LoggedInMode.LOGGED_IN_MODE_SERVER)
preferenceHelperImp.setAccessToken(it.data.body()?.payload?.accessToken)
preferenceHelperImp.setRefreshToken(it.data.body()?.payload?.refreshToken)
preferenceHelperImp.setUserInfo(Gson().toJson(TokenInfo.initFromToken(
it.data.body()?.payload?.accessToken!!)))

Session.current.userInfo =
Gson().fromJson(preferenceHelperImp.getUserInfo(),
TokenInfo::class.java)

response.request.newBuilder()
.header("Authorization", it.data.body()?.payload?.accessToken!!)
.build()
}
is State.Fail -> {
Session.current.isRefreshTokenFail.postValue(true)
}
is State.Error -> {
Session.current.isRefreshTokenFail.postValue(true)
}
}
}
}
return null
}

private fun getUpdatedRefreshToken(refreshTokenRequest: RefreshTokenRequest): Flow<State<LoginResponse>> {
return object :
NetworkBoundRepository<LoginResponse>() {
override suspend fun fetchFromRemote(): retrofit2.Response<LoginResponse> =
tokenApi.getRefreshToken(refreshTokenRequest)
}.asFlow()
}
}

最佳答案

你能试试 typealias 吗?

typealias OnAuthSuccess = () -> Unit
typealias OnAuthFailure = () -> Unit
class TokenAuthenticator (){...
override fun authenticate(onAuthSuccess: OnAuthSuccess,onAuthFailure: OnAuthFailure, route: Route?, response: Response): Request? {
when (it) {
is State.Success -> {
onAuthSuccess.invoke()
}
is State.Fail -> {
onAuthFailure.invoke()
}
}

关于android - 如何在 token 验证器和注销用户中显示错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69161754/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com