Search code examples
androidkotlindependency-injectionkoin

Is it possible to create different instances of the same object and access them by passing parameters to get() function in Koin?


I am using Koin as a DI for my app. I created a module:

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)
        }
    } 
}

How can I create different HttpClient or Retrofit instances which have different parameters set or has different instantiation? For instance, in some cases, I might need OkHttpClient with AutheniticationInterceptor and in some other cases my client might not need to use it.

Can I pass some parameters when calling get() so that I can get different instances? Any suggestions would be apprieciated.


Solution

  • You can use named properties - e.g.

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

    Then in your get() method you pass the name, e.g.

    .client(get(named("auth")))