Is it possible to create different instances of the same object and access them by passing parameters to get() function in Koin?(是否可以创建同一对象的不同实例,并通过将参数传递给KOIN中的get()函数来访问它们?)
问题描述
我正在使用KOIN作为我的应用程序的DI。我创建了一个模块:
object NetworkModule {
fun get() = module {
single {
val authenticationInterceptor = Interceptor { chain ->
// Request customization goes here
}
OkHttpClient.Builder()
.connectTimeout(15, TimeUnit.SECONDS)
.readTimeout(60, TimeUnit.SECONDS)
.writeTimeout(60, TimeUnit.SECONDS)
.addInterceptor(authenticationInterceptor) //Not all clients might have this interceptor
.build()
}
single {
Retrofit.Builder()
.baseUrl("example.com")
.client(get(/* I would like to send some paramter here */))
.addConverterFactory(GsonConverterFactory.create(get()))
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build()
.create(Api::class.java)
}
}
}
如何创建设置了不同参数或实例化不同的HttpClient
或Retrofit
实例?例如,在某些情况下,我可能需要OkHttpClient
和AutheniticationInterceptor
,而在其他一些情况下,我的客户端可能不需要使用它。
是否可以在调用get()
时传递一些参数,以便获取不同的实例?任何建议都会被提出来。
推荐答案
您可以使用命名属性,例如
single<OkHttpClient>(named("auth")){
// here you pass the version with authinterceptor
}
single<OkHttpClient>(named("noAuth")){
// here you pass the version without authinterceptor
}
然后在get()方法中传递名称,例如
.client(get(named("auth")))
这篇关于是否可以创建同一对象的不同实例,并通过将参数传递给KOIN中的get()函数来访问它们?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!