Skip to content

Instantly share code, notes, and snippets.

@ahulyk
Last active August 19, 2020 11:41
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ahulyk/149aa35b228f0711bc530cb6dcc0e6ce to your computer and use it in GitHub Desktop.
Save ahulyk/149aa35b228f0711bc530cb6dcc0e6ce to your computer and use it in GitHub Desktop.
Glide 4 inject custom OkHttp client using Dagger 2
@Singleton
@Component(
modules = [
NetModule::class,
AndroidInjectionModule::class,
GlideBuilderModule::class
]
)
interface AppComponent : AndroidInjector<App> {
@Component.Factory
abstract class Factory : AndroidInjector.Factory<App>
}
@Module
abstract class GlideBuilderModule {
@ContributesAndroidInjector
abstract fun bind(): OkHttpGlideModule
}
@Module
class NetModule {
@Provides
@Singleton
fun provideLoggingInterceptor(): HttpLoggingInterceptor {
return HttpLoggingInterceptor().apply { level = if (DEBUG) BODY else NONE }
}
@Provides
@Singleton
fun provideOkHttpClient(
loggingInterceptor: HttpLoggingInterceptor
): OkHttpClient = OkHttpClient.Builder()
.connectTimeout(15, TimeUnit.SECONDS)
.readTimeout(15, TimeUnit.SECONDS)
.writeTimeout(15, TimeUnit.SECONDS)
.addNetworkInterceptor(loggingInterceptor)
.build()
@Provides
@Singleton
@Named("serverUrl")
fun provideServerUrl(context: Context): String {
return "your.server.url"
}
}
@Excludes(OkHttpLibraryGlideModule::class)
@GlideModule
class OkHttpGlideModule : AppGlideModule() {
@Inject
lateinit var client: OkHttpClient
override fun registerComponents(context: Context, glide: Glide, registry: Registry) {
Timber.i("Registering Glide components...")
(context.applicationContext as App).androidInjector().inject(this)
registry.replace(GlideUrl::class.java, InputStream::class.java, OkHttpUrlLoader.Factory(client))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment