gpt4 book ai didi

android - 如何像这样注入(inject)网络模块?

转载 作者:行者123 更新时间:2023-11-29 02:20:02 25 4
gpt4 key购买 nike

我想不出如何注入(inject)网络模块。我尝试找到很多方法在 Dagger 2 中注入(inject)网络模块。但我无法解决这个问题。请帮助我。

abstract class BaseRepository protected constructor() {
init {
val logger = HttpLoggingInterceptor()
logger.level = HttpLoggingInterceptor.Level.BODY
val client = OkHttpClient.Builder()
.connectTimeout(1, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.writeTimeout(15, TimeUnit.SECONDS)
.addInterceptor(logger)
.build()

val retrofit = Retrofit.Builder()
.baseUrl(BuildConfig.BASE_URL)
.addConverterFactory(GsonConverterFactory.create(Gson()))
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.client(client)
.build()

mTheApi = retrofit.create<AttendanceApi>(AttendanceApi::class.java)
}
}

我试过这个模块,但没用。

class NetworkModule {
companion object {
private const val NAME_BASE_URL = "NAME_BASE_URL"
}

@Provides
@Named(NAME_BASE_URL)
fun provideBaseUrlString()=
"http://attendance.saltcloudserver.com/api/"

@Provides
@Singleton
fun provideHttpClient()=OkHttpClient()

@Provides
@Singleton
fun provideRetrofit(interceptor: HttpLoggingInterceptor): OkHttpClient {
return OkHttpClient.Builder()
.connectTimeout(1, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.writeTimeout(15, TimeUnit.SECONDS)
.addInterceptor(interceptor)
.build()
}
}

我期待输出,但我无法注入(inject)它。

最佳答案

要使 dagger 识别,您需要指定它是 Module。为此,您需要向类添加 @Module 注释,我发现您当前的实现中缺少该注释。

@Module
class NetworkModule {
companion object {
private const val NAME_BASE_URL = "NAME_BASE_URL"
}

@Provides
@Named(NAME_BASE_URL)
fun provideBaseUrlString()=
"http://attendance.saltcloudserver.com/api/"

@Provides
@Singleton
fun provideHttpClient()=OkHttpClient()

@Provides
@Singleton
fun provideRetrofit(interceptor: HttpLoggingInterceptor): OkHttpClient {
return OkHttpClient.Builder()
.connectTimeout(1, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.writeTimeout(15, TimeUnit.SECONDS)
.addInterceptor(interceptor)
.build()
}
}

关于android - 如何像这样注入(inject)网络模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56831941/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com