小编Abh*_*bey的帖子

Koin依赖注入

我有一个使用Dagger 2进行依赖注入的类。现在我想切换到Koin进行依赖注入。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)
}
Run Code Online (Sandbox Code Playgroud)

android kotlin koin

0
推荐指数
1
解决办法
621
查看次数

标签 统计

android ×1

koin ×1

kotlin ×1