Reputation: 9207
Suppose I have a module in which one binding depends on another:
class MyModule : Module(){
init {
bind(SettingsStorage::class.java).to(PreferencesBasedSettingsStorage::class.java)
// how to use createOkHttpClient here?
// how to get instance of SettingsStorage to pass to it?
bind(OkHttpClient::class.java).to?(???)
}
private fun createOkHttpClient(settingsStorage: SettingsStorage): OkHttpClient {
return OkHttpClient.Builder()
.addNetworkInterceptor(MyInterceptor(settingsStorage))
.build()
}
}
Here I can create OkHttpClient
only having an instance of another binding, namely SettingsStorage
. But how to do that?
Currently I see no way to get instance of SettingsStorage
binding inside a module to pass it to createOkHttpClient()
In Dagger I would've simply created two provider methods with appropriate arguments like
fun provideSessionStorage(/*...*/): SessionStorage { /* ... */ }
fun provideOkHttpclient(sessionStorage: SessionStorage): OkHttpClient {
return OkHttpClient.Builder()
.addNetworkInterceptor(MyInterceptor(settingsStorage))
.build()
}
And it would figure all out by itself and passed appropriate instance of sessionStorage to a second provider function.
How to achieve the same inside a Toothpick module?
Upvotes: 3
Views: 519
Reputation: 38168
It's simple with TP:
class MyModule : Module(){
init {
bind(SettingsStorage::class.java).to(PreferencesBasedSettingsStorage::class.java)
// how to use createOkHttpClient here?
// how to get instance of SettingsStorage to pass to it?
bind(OkHttpClient::class.java).toProvider(OkHttpClientProvider::class)
}
}
and then you define a provider (sorry I don't use Kotlin):
class OkHttpClientProvider implements Provider<OkHttpClient> {
@Inject SettingsStorage settingsStorage;
public OkHttpClient get() {
return OkHttpClient.Builder()
.addNetworkInterceptor(MyInterceptor(settingsStorage))
.build()
}
}
Your provider will use the first binding to provide the OkHttp client.
Upvotes: 2