android - 是否可以创建同一对象的不同实例并通过将参数传递给 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")))
推荐阅读
- python - yammer 是否通过 API 支持富文本格式
- algorithm - 从数组 (X1,X2,Y) 中找到三元组,使得 X1*X2=Y^2
- python - 当 locs 存在且数据存在时,df.iloc 返回空
- angular - Angular observable subscribe 在 next() 和 error() 上调用相同的方法
- python - 压缩列表中的多个 lambda 函数未执行
- osgi - 是否有一种简单的方法来列出接口的消费者组件?
- c++ - 如何用修改后的十六进制 ASCII 符号替换 ByteArray 元素?
- python - 如何使用 Ajax 和 CherryPy 运行 python 脚本以从 Web 界面通过 SSH 连接到 Raspberry Pi Zero
- azure - 打开逻辑应用程序时:发生未知错误(代码 502)
- java - 如何使用 cucumber 和 selenium web 驱动程序为 web 应用程序双语(英语和阿拉伯语)执行相同的测试步骤