我正在用Kotlin和Dagger 2开发一个Android项目。我有一个NetworkModule
,它应该提供一个单一的Retrofit实例。其中我定义了所有这些提供者函数。
下面的所有代码片段都在网络模块
中:
@Module
object NetworkModule {
...
}
我的第一个问题:
我想为OkHttpClient
提供一个HttpLoggingInterceptor
的单例。这是我尝试的:
@Provides
internal fun provideLoggingInterceptor(): Interceptor {
// compiler error: Unresolved reference 'setLevel', unresolved reference 'Level'
return HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)
}
但我遇到了一个编译错误:未解析引用“setLevel”
和Unresolved引用“Level”
,如何消除它?
我的第二个问题:
我将OkHttpClient提供程序函数定义为:
@Provides
internal fun provideOkHttpClient(loggingInterceptor: Interceptor): OkHttpClient {
return OkHttpClient.Builder()
.addInterceptor(loggingInterceptor)
...
.build()
}
我如何才能使它只addInterceptor(loggingInterceptor)
当它在调试模型,而在发布模式下不添加HttpLoggingInterceptor
在上述提供程序函数?
对于您的第一个问题,您确定您有正确的依赖项吗?
或者,既然你在科特林,就这样试试:
@JvmStatic
@Provides
@Singleton
fun provideLoggingInterceptor(): HttpLoggingInterceptor {
val httpLoggingInterceptor = HttpLoggingInterceptor()
httpLoggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
return httpLoggingInterceptor
}
对于你的第二个问题:
我如何才能使它只有addInterceptor(loggingInterceptor)时,它是在调试模型,而在发布模式不添加HttpLoggingInterceptor在上述提供程序功能?
@Provides
@JvmStatic
@Singleton
fun provideOkHttpClient(interceptor: Interceptor): OkHttpClient{
val okhttpBuilder = OkHttpClient.Builder() //and every other method after it except build() would return a Builder (Builder pattern)
if(BuildConfig.DEBUG){
okHttpBuilder.addInterceptor(interceptor)
}
return okHttpBuilder.build()
}
请注意@JvmStatic
和@Singleton
注释,因为您正在使用Singleton。一个用于JVM,另一个用于作用域。
要仅在 DEBUG 版本中设置记录器,您有两个选择
https://stackoverflow.com/a/23844716/1542667
HttpLoggingInterceptor l = ...;
if (!BuildConfig.DEBUG) {
l.level(HttpLoggingInterceptor.Level.NONE);
}
https://medium . com/@ birajdpatel/avoid-nullable-dependencies-in-dagger 2-with-binds optional of-c 3 ad 8 a 8 FD e2c