【发布时间】:2021-04-23 19:25:27
【问题描述】:
我正在使用 Koin 将令牌传递给请求的 GET 方法。但在授权新用户后,旧令牌被保存。要获取新的访问令牌,您需要退出应用程序,重新登录并登录。
如何在单击注销按钮时清除 Koin 依赖项?
val appModule = module {
factory { provideToken(provideSharedPreferences(androidContext())) }
}
private fun provideSharedPreferences(context: Context): SharedPreferences =
context.getSharedPreferences("token", Context.MODE_PRIVATE)
fun provideToken(sharedPreferences: SharedPreferences): String =
sharedPreferences.getString("key", "")
注入令牌:
class VkRetrofitDataSource (
private val vkRetrofitApi: VkRetrofitApi,
private val ioDispatcher: CoroutineDispatcher,
) : VkNetworkDataSource, KoinComponent {
private val accessToken: String by inject()
override suspend fun getUserInfo(
fields: String,
apiVersion: String
): Result<ResponseResultUser> =
withContext(ioDispatcher) {
val response = vkRetrofitApi.getUserInfo(fields, apiVersion, accessToken)
val userResponse = response.body()
Timber.d("Token $userResponse")
return@withContext if (response.isSuccessful && userResponse != null) {
Result.Success(userResponse)
}
}
【问题讨论】:
-
你为什么要设置你的 DI 只是为了注入一个字符串?如果有任何东西注入 SharedPreferences 对象,那么您可以从共享首选项中获取它并始终拥有正确的令牌
标签: android kotlin dependency-injection koin