Last active
August 19, 2020 11:41
-
-
Save ahulyk/149aa35b228f0711bc530cb6dcc0e6ce to your computer and use it in GitHub Desktop.
Glide 4 inject custom OkHttp client using Dagger 2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Singleton | |
@Component( | |
modules = [ | |
NetModule::class, | |
AndroidInjectionModule::class, | |
GlideBuilderModule::class | |
] | |
) | |
interface AppComponent : AndroidInjector<App> { | |
@Component.Factory | |
abstract class Factory : AndroidInjector.Factory<App> | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Module | |
abstract class GlideBuilderModule { | |
@ContributesAndroidInjector | |
abstract fun bind(): OkHttpGlideModule | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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" | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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