Skip to content

Instantly share code, notes, and snippets.

@abos3d
Last active June 22, 2021 08:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abos3d/8e70f0adbe929ad4b4dd848f01aa1f35 to your computer and use it in GitHub Desktop.
Save abos3d/8e70f0adbe929ad4b4dd848f01aa1f35 to your computer and use it in GitHub Desktop.
Hilt impl
package com.cleanarchitectkotlinflowhiltsimplestway.utils
import android.content.Context
import com.cleanarchitectkotlinflowhiltsimplestway.data.APIs
import com.cleanarchitectkotlinflowhiltsimplestway.presentation.App
import com.google.gson.GsonBuilder
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import okhttp3.Cache
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.io.File
import java.util.concurrent.TimeUnit
import javax.inject.Singleton
@Module
@Suppress("unused")
@InstallIn(SingletonComponent::class)
class NetworkModule {
@Singleton
@Provides
fun provideApplication(@ApplicationContext app: Context): App {
return app as App
}
@Provides
@Singleton
fun provideRetrofit(client: OkHttpClient): Retrofit {
return Retrofit.Builder().baseUrl(Constants.BASE_URL).client(client)
.addConverterFactory(GsonConverterFactory.create(GsonBuilder().create()))
.build()
}
private val READ_TIMEOUT = 30
private val WRITE_TIMEOUT = 30
private val CONNECTION_TIMEOUT = 10
private val CACHE_SIZE_BYTES = 10 * 1024 * 1024L // 10 MB
@Provides
@Singleton
fun provideOkHttpClient(
headerInterceptor: Interceptor,
cache: Cache
): OkHttpClient {
val okHttpClientBuilder = OkHttpClient().newBuilder()
okHttpClientBuilder.connectTimeout(CONNECTION_TIMEOUT.toLong(), TimeUnit.SECONDS)
okHttpClientBuilder.readTimeout(READ_TIMEOUT.toLong(), TimeUnit.SECONDS)
okHttpClientBuilder.writeTimeout(WRITE_TIMEOUT.toLong(), TimeUnit.SECONDS)
okHttpClientBuilder.cache(cache)
okHttpClientBuilder.addInterceptor(headerInterceptor)
return okHttpClientBuilder.build()
}
@Provides
@Singleton
fun provideHeaderInterceptor(): Interceptor {
return Interceptor {
val requestBuilder = it.request().newBuilder()
//hear you can add all headers you want by calling 'requestBuilder.addHeader(name , value)'
it.proceed(requestBuilder.build())
}
}
@Provides
@Singleton
internal fun provideCache(context: Context): Cache {
val httpCacheDirectory = File(context.cacheDir.absolutePath, "HttpCache")
return Cache(httpCacheDirectory, CACHE_SIZE_BYTES)
}
@Provides
@Singleton
fun provideContext(application: App): Context {
return application.applicationContext
}
@Provides
@Singleton
fun provideApi(retrofit: Retrofit): APIs {
return retrofit.create(APIs::class.java)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment