Dagger 2模块中OkHttpClient提供HttpLoggingInterceptor实例的两个问题

Two questions about providing instance of HttpLoggingInterceptor for OkHttpClient in Dagger 2 module

我正在使用 Kotlin 和 Dagger 2 开发一个 Android 项目。我有一个 NetworkModule 它应该提供 Retrofit 的单例实例。我在其中定义了所有这些提供者功能。

下面的所有代码片段都在 NetworkModule :

@Module
object NetworkModule {
   ...
}

我的第一个问题:

我想为 OkHttpClient 提供 HttpLoggingInterceptor 的单例。这是我尝试过的:

@Provides
internal fun provideLoggingInterceptor(): Interceptor {
    // compiler error: Unresolved reference 'setLevel', unresolved reference 'Level'
    return HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)
}

但是我得到一个编译错误:Unresolved reference 'setLevel'Unresolved reference 'Level',如何摆脱它?

我的第二个问题:

我将我的 OkHttpClient 提供程序函数定义为:

@Provides
internal fun provideOkHttpClient(loggingInterceptor: Interceptor): OkHttpClient {
        return OkHttpClient.Builder()
                        .addInterceptor(loggingInterceptor)
                        ...
                        .build()
}

我怎样才能做到在调试模式下只有addInterceptor(loggingInterceptor),而在发布模式下不在上面的提供程序函数中添加HttpLoggingInterceptor

要仅在 DEBUG 构建中设置记录器,您有两个选择

  1. 根据Build.DEBUG
  2. 使用NONE级别

HttpLoggingInterceptor l = ...;

if (!BuildConfig.DEBUG) {
    l.level(HttpLoggingInterceptor.Level.NONE);
}
  1. 使用 Dagger optional/nullable 避免设置拦截器

https://medium.com/@birajdpatel/avoid-nullable-dependencies-in-dagger2-with-bindsoptionalof-c3ad8a8fde2c

关于你的第一个问题,你确定你有正确的依赖关系吗?

或者因为你使用的是 Kotlin,可以这样尝试:

@JvmStatic
@Provides
@Singleton
fun provideLoggingInterceptor(): HttpLoggingInterceptor {
    val httpLoggingInterceptor = HttpLoggingInterceptor()
    httpLoggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
    return httpLoggingInterceptor
}

第二个问题:

How can I make it so that only addInterceptor(loggingInterceptor) when it is in the debug model, whereas in release mode not add the HttpLoggingInterceptor in the above provider function?

@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 注释,因为您使用的是单例。一个用于 JVM,另一个用于范围界定。