【发布时间】:2018-08-31 06:59:46
【问题描述】:
Dagger 2 正在生成多个改装拦截器实例,尽管在 dagger 模块中将其标记为单例。现在的问题是 AuthorizationInterceptor 构造函数被调用了两次,我不明白为什么,因为我在从登录 API 获取结果后设置的标头设置为不同的 Interceptor 实例,同时调用其他一些需要的 API authenticationToken 令牌未设置。
这是我的 ApiModule
@Module
open class ApiModule {
@Provides
@Singleton
fun provideHttpLoggingInterceptor(): HttpLoggingInterceptor {
val loggingInterceptor = HttpLoggingInterceptor()
loggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
return loggingInterceptor
}
@Provides
@Singleton
fun provideHeaderInterceptor(): Interceptor {
return AuthorizationInterceptor()
}
@Provides
@Singleton
fun provideHttpClient(interceptor: HttpLoggingInterceptor, headerInterceptor: Interceptor): OkHttpClient {
return OkHttpClient.Builder()
.addInterceptor(interceptor)
.addInterceptor(headerInterceptor)
.build()
}
@Provides
@Singleton
fun provideMoshi(): Moshi {
return Moshi.Builder()
.build()
}
@Provides
@Singleton
fun provideRetrofit(client: OkHttpClient, moshi: Moshi, apiConfig: ApiConfig): Retrofit {
return Retrofit.Builder()
.baseUrl(apiConfig.baseUrl)
.client(client)
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(MoshiConverterFactory.create(moshi))
.build()
}
@Provides
@Singleton
fun provideFrappApi(retrofit: Retrofit): FrappApi {
return retrofit.create(FrappApi::class.java)
}
这是我的 AuthorizationInterceptor 类
@Singleton
class AuthorizationInterceptor @Inject constructor() : Interceptor {
override fun intercept(chain: Interceptor.Chain?): Response {
val request = chain?.request()
val requestBuilder = request?.newBuilder()
if (request?.header("No-Authorization") == null && authorization.isNotEmpty()) {
requestBuilder?.addHeader("Authorization", authorization)
}
return chain?.proceed(requestBuilder!!.build())!!
}
private var authorization: String = ""
fun setSessionToken(sessionToken: String) {
this.authorization = sessionToken
}
}
【问题讨论】:
标签: android kotlin retrofit dagger