使用参数在Koin模块中创建不同的属性

时间:2019-06-17 11:01:38

标签: android kotlin dependency-injection koin

我正在将Koin用作我的应用程序的DI。我创建了一个模块:

object NetworkModule {

fun get() = module {
    single {
        val localStorage: LocalStorage = get()
        val loggingInterceptor = HttpLoggingInterceptor()
        loggingInterceptor.level = if (BuildConfig.DEBUG) HttpLoggingInterceptor.Level.BODY
        else HttpLoggingInterceptor.Level.NONE

        val authInterceptor = Interceptor { chain ->
            val original = chain.request()

            // Request customization: add request headers
            val requestBuilder = original.newBuilder()

            if (localStorage.deviceToken != null) {
                requestBuilder.addHeader("device_token", localStorage.deviceToken!!)
            }

            if (localStorage.authToken != null) {
                requestBuilder.addHeader("access_token", localStorage.authToken!!)
            }

            val request = requestBuilder.build()
            chain.proceed(request)
        }

        OkHttpClient.Builder()
            .connectTimeout(15, TimeUnit.SECONDS)
            .readTimeout(60, TimeUnit.SECONDS)
            .writeTimeout(60, TimeUnit.SECONDS)
            .addInterceptor(authInterceptor)
            .addInterceptor(loggingInterceptor)
            .build()
    }

    single {
        Retrofit.Builder()
            .baseUrl(Const.BASE_API_URL)
            .client(get())
            .addConverterFactory(GsonConverterFactory.create(get()))
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .build()
            .create(Api::class.java)

在某些请求中,我可能使用AutheniticationInterceptor,而在另一些请求中,我可能不使用。考虑到这种情况,我该如何以不同的方式构建HttpClientRetrofit

我可以传递一些参数吗?我只是在这里迷路了。任何建议将不胜感激。

2 个答案:

答案 0 :(得分:3)

您可以使用命名属性-例如

single<OkHttpClient>("auth"){
// here you pass the version with authinterceptor
}
single<OkHttpClient>("noAuth"){
// here you pass the version without authinterceptor
}

然后在您的get()方法中传递名称,例如

.client(get("auth"))

答案 1 :(得分:1)

  

您可以按照下面的步骤进行操作(将koin最新版本用于命名属性)。      

single-声明给定类型的单例定义。 Koin仅保留此定义的一个实例

     

factory-声明给定类型的工厂定义。 Koin给出了新的   每次实例

factory(named("HEADERS")) {
        val map = it.get<MutableMap<String, String>>(0)
        Interceptor { chain ->
            val original = chain.request()
            val request = original.newBuilder()
            map.forEach { entry ->
                request.addHeader(entry.key, entry.value)
            }
            chain.proceed(request.build())
        }
    }

factory(named("auth")) {
        OkHttpClient.Builder().apply {
            map["AUTHORIZATION"] = "token"

            readTimeout(1, TimeUnit.MINUTES)
            connectTimeout(2, TimeUnit.MINUTES)
            writeTimeout(1, TimeUnit.MINUTES)
            addInterceptor(get(named("HEADERS"), parameters = {
               parametersOf(map)
            }))
        }.build()
    }

factory(named("auth")) {
        Retrofit.Builder()
                .baseUrl("base_url")
                .client(get(named("auth")))
                //.addCallAdapterFactory()
                .addConverterFactory(GsonConverterFactory.create())
                .build()
                .create(ApiService::class.java)
    }

single(named("noAuth")) {
        val map = mutableMapOf(ACCEPT to CONTENT_TYPE)
        OkHttpClient.Builder().apply {
            readTimeout(1, TimeUnit.MINUTES)
            connectTimeout(2, TimeUnit.MINUTES)
            writeTimeout(1, TimeUnit.MINUTES)
            addInterceptor(get(named("HEADERS"), parameters = {
                parametersOf(map)
            }))

        }.build()
    }

single(named("noAuth")) {
        Retrofit.Builder()
                .baseUrl("base_url")
                .client(get(named("noAuth")))
                //.addCallAdapterFactory()
                .addConverterFactory(GsonConverterFactory.create())
                .build()
                .create(ApiService::class.java)
    }