是否可以创建同一对象的不同实例,并通过将参数传递给KOIN中的get()函数来访问它们? [英] Is it possible to create different instances of the same object and access them by passing parameters to get() function in Koin?

查看:53
本文介绍了是否可以创建同一对象的不同实例,并通过将参数传递给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)
        }
    } 
}

如何创建设置了不同参数或实例化不同的HttpClientRetrofit实例?例如,在某些情况下,我可能需要OkHttpClientAutheniticationInterceptor,而在其他一些情况下,我的客户端可能不需要使用它。

是否可以在调用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()函数来访问它们?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆