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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With