admin管理员组

文章数量:1391947

I have Koin in my project, and I instantiate retrofit like this in the appmodule:

single<ApiService> {
    Retrofit.Builder()
        .baseUrl(";)
        .addConverterFactory(JacksonConverterFactory.create())
        .addConverterFactory(ScalarsConverterFactory.create())
        .build()
        .create(ApiService::class.java)
}

The issue is that I need to parametrize the baseUrl to retrofit, because the user can change it with a textfield. How can I tell Koin that must initialize this singleton for retrofit with a dinamically passed variable? I only found very complex samples for doing this using factory instead of singleton, and doing it with field injection instead of constructor injection, so I hope there is a simpler way.

I have Koin in my project, and I instantiate retrofit like this in the appmodule:

single<ApiService> {
    Retrofit.Builder()
        .baseUrl("https://myurl.es")
        .addConverterFactory(JacksonConverterFactory.create())
        .addConverterFactory(ScalarsConverterFactory.create())
        .build()
        .create(ApiService::class.java)
}

The issue is that I need to parametrize the baseUrl to retrofit, because the user can change it with a textfield. How can I tell Koin that must initialize this singleton for retrofit with a dinamically passed variable? I only found very complex samples for doing this using factory instead of singleton, and doing it with field injection instead of constructor injection, so I hope there is a simpler way.

Share Improve this question asked Mar 12 at 19:01 NullPointerExceptionNullPointerException 37.8k80 gold badges231 silver badges405 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

this is a bit tricky .
we have more than one way to get params in koin .
1- from dependency graph
so you will add your named dependency (because I think will need more than one String)
for me I prefer to do that with annotations

@Named
annotation class YourAnnotation

or in DSL like that

single(named("yourName")) { "what ever string" }

and after that you can get your string from the graph like that

single { ApiService(get(named<YourAnnotation>())) }

or in DSL

single { ApiService(get(named("yourName"))) } 

2- pass it with params

val apiService : APIService by inject { parametersOf(firstParam,secondParam) 

and in your module you can access your params like this

single { params -> Presenter(params[0],params[1]) }

hope this will help you .

本文标签: androidHow to pass a parameter to a Koin single in a Koin moduleStack Overflow