问题描述
我在使用Dagger 2在运行时更新令牌时遇到问题。
这是场景:
我有一个更改密码的屏幕。当我成功更新密码时,当前的jwt令牌将无效,并且我需要从更新令牌响应中存储新令牌,然后将该令牌存储在SharedPreferences中。但是问题是当我存储令牌时。它在sharedprefernces中进行了更新,但不会在我构建Retrofit实例(授权标头)的Daggergraph中更新值。
下面是我的代码:
AppComponent.kt
@Singleton
@Component(
modules = [StorageModule::class,AppModule::class,viewmodelModule::class]
)
interface AppComponent {
@Component.Factory
interface Factory {
fun create(@BindsInstance context: Context): AppComponent
}
fun inject(activity: SplashActivity)
fun inject(activity: LoginActivity)
fun inject(activity: MainActivity)
fun inject(activity: ChangePasswordActivity)
}
AppModule.kt
@Module
class AppModule {
@Singleton
@Provides
fun provideAuthInterceptor(sharedPreferencesSources: SharedPreferencesSources): Interceptor {
return AuthInterceptor(sharedPreferencesSources.tokenApi())
}
@Singleton
@Provides
fun provideApiService(
authInterceptor: Interceptor
): SharedProductClient {
return Network.retrofitClient(authInterceptor = authInterceptor)
.create(SharedProductClient::class.java)
}
@Singleton
@Provides
fun provideAppRepository(apiService: SharedProductClient): AppRepository {
return AppRepositoryImpl(apiService)
}
@Singleton
@Provides
fun provideAppUseCase(appRepository: AppRepository): AppUseCase {
return AppUseCase(appRepository)
}
@Singleton
@Provides
fun provideAppScheduler(): SchedulerProvider = AppSchedulerProvider()
}
StorageModule.kt
@Module
class StorageModule {
@Singleton
@Provides
fun provideSharedPreferences(context: Context): SharedPreferences {
return context.getSharedPreferences(SharedPrefName,Context.MODE_PRIVATE)
}
@Singleton
@Provides
fun provideSharedPreferencesSource(sharedPrefInstance: SharedPreferences): SharedPreferencesSources {
return SharedPreferencesSourcesImpl(sharedPrefInstance)
}
companion object {
const val SharedPrefName = "share_product_prefs"
}
}
AuthInterceptor.kt
class AuthInterceptor constructor(
private val token: String
) : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response = chain.run {
proceed(
request()
.newBuilder()
.addHeader("Accept","application/json")
.addHeader("Authorization","Bearer $token")
.build()
)
}
}
任何建议都会对我有帮助。谢谢!
解决方法
这是因为您在创建String
时仅传递了令牌的AuthInterceptor
实例。
您应该提供一种在需要时从SharedPreferences
动态获取令牌的方式(例如接口)。
这是一种实现方式:
- 在
token:String
构造函数中将AuthInterceptor
更改为函数类型(并在需要时使用它):
class AuthInterceptor constructor(
private val tokenProvider: () -> String
) : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response = chain.run {
proceed(
request()
.newBuilder()
.addHeader("Accept","application/json")
.addHeader("Authorization","Bearer ${tokenProvider.invoke()}")
.build()
)
}
}
- 在创建
AuthInteceptor
时,请构建lambda以动态引用SharedPreferences
@Module
class AppModule {
@Singleton
@Provides
fun provideAuthInterceptor(sharedPreferencesSources: SharedPreferencesSources): Interceptor {
return AuthInterceptor(){ sharedPreferencesSources.tokenApi() }
}
//...
}
这样,每次进行api调用时,tokenProvider
将被invoked
(将访问SharedPreferences
),而不是在创建AuthInterceptor
时仅被访问一次