gpt4 book ai didi

android - 使用 Koin 进行依赖注入(inject)

转载 作者:行者123 更新时间:2023-12-05 00:09:59 25 4
gpt4 key购买 nike

我有一个使用 Dagger 2 进行依赖注入(inject)的类。现在我想切换到 Koin 进行依赖注入(inject)。 Koin 中有模块,我想从类中创建一个模块或者可以做的任何事情。

@Module
class NetModule(private val baseUrl: String) {

@Provides
@Singleton
fun providesOkHttpClient(
httpLoggingInterceptor: HttpLoggingInterceptor): OkHttpClient = OkHttpClient.Builder().addInterceptor(
httpLoggingInterceptor).build()

@Provides
@Singleton
fun provideLoggingInterceptor(): HttpLoggingInterceptor {
val interceptor = HttpLoggingInterceptor(
HttpLoggingInterceptor.Logger { message -> Logger.d("NETWORK: $message") })
interceptor.level = HttpLoggingInterceptor.Level.NONE
return interceptor
}

@Provides
@Singleton
fun providesMoshi(): Moshi = Moshi.Builder().add(KotlinJsonAdapterFactory()).build()

@Provides
@Singleton
fun providesRetrofit(okHttpClient: OkHttpClient, moshi: Moshi): Retrofit {
return Builder().client(okHttpClient).baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build()
}

@Provides
@Singleton
fun providesApiInterface(retrofit: Retrofit): ApiInterface = retrofit.create(
ApiInterface::class.java)
}

最佳答案

Koin 使用 DSL 来描述模块。通常你会在顶层声明模块本身。由于您需要提供 baseUrl,因此您必须为其创建一个工厂。

@Provides 注释是完全不相关的,但是 @Singleton 需要翻译并且用 single 来完成。要检索依赖项,只需调用 get()

fun netModule(baseUrl: String) = module {

single {
HttpLoggingInterceptor(
HttpLoggingInterceptor.Logger { message ->
Logger.d("NETWORK: $message")
}).apply {
level = HttpLoggingInterceptor.Level.NONE
}
}

single {
OkHttpClient.Builder()
.addInterceptor(get<HttpLoggingInterceptor>())
.build()
}


single {
Moshi.Builder()
.add(KotlinJsonAdapterFactory())
.build()
}

single {
Retrofit.Builder()
.client(get())
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build()
}

single { get<Retrofit>().create(ApiInterface::class.java) }
}

关于android - 使用 Koin 进行依赖注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53592233/

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