|
| 1 | +package io.petros.github.data.di.dagger |
| 2 | + |
| 3 | +import android.content.Context |
| 4 | +import com.google.gson.Gson |
| 5 | +import dagger.Module |
| 6 | +import dagger.Provides |
| 7 | +import io.petros.github.data.BuildConfig |
| 8 | +import io.petros.github.data.R |
| 9 | +import io.petros.github.data.getLong |
| 10 | +import io.petros.github.data.network.WebService |
| 11 | +import io.petros.github.data.network.interceptor.HeaderInterceptor |
| 12 | +import io.petros.github.data.network.rest.RestApi |
| 13 | +import io.petros.github.data.network.rest.RestClient |
| 14 | +import okhttp3.OkHttpClient |
| 15 | +import okhttp3.logging.HttpLoggingInterceptor |
| 16 | +import retrofit2.Retrofit |
| 17 | +import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory |
| 18 | +import retrofit2.converter.gson.GsonConverterFactory |
| 19 | +import java.util.concurrent.TimeUnit |
| 20 | +import javax.inject.Singleton |
| 21 | + |
| 22 | +@Module |
| 23 | +class NetworkModule { |
| 24 | + |
| 25 | + @Provides |
| 26 | + @Singleton |
| 27 | + fun providesGson() = Gson() |
| 28 | + |
| 29 | + @Provides |
| 30 | + fun provideHttpLoggingInterceptor(): HttpLoggingInterceptor { |
| 31 | + val logging = HttpLoggingInterceptor() |
| 32 | + logging.level = HttpLoggingInterceptor.Level.BODY |
| 33 | + return logging |
| 34 | + } |
| 35 | + |
| 36 | + @Provides |
| 37 | + @Singleton |
| 38 | + fun provideOkHttpClient( |
| 39 | + context: Context, |
| 40 | + headerInterceptor: HeaderInterceptor, |
| 41 | + loggingInterceptor: HttpLoggingInterceptor |
| 42 | + ): OkHttpClient { |
| 43 | + val okHttpBuilder = OkHttpClient.Builder() |
| 44 | + .connectTimeout(context.getLong(R.integer.network_timeout), TimeUnit.MILLISECONDS) |
| 45 | + okHttpBuilder.addInterceptor(headerInterceptor) |
| 46 | + if (BuildConfig.DEBUG) okHttpBuilder.addInterceptor(loggingInterceptor) |
| 47 | + return okHttpBuilder.build() |
| 48 | + } |
| 49 | + |
| 50 | + @Provides |
| 51 | + @Singleton |
| 52 | + fun provideRetrofit(context: Context, gson: Gson, httpClient: OkHttpClient): Retrofit { |
| 53 | + return Retrofit.Builder() |
| 54 | + .baseUrl(context.getString(R.string.rest_github_url)) |
| 55 | + .addConverterFactory(GsonConverterFactory.create(gson)) |
| 56 | + .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) |
| 57 | + .client(httpClient) |
| 58 | + .build() |
| 59 | + } |
| 60 | + |
| 61 | + @Provides |
| 62 | + @Singleton |
| 63 | + fun provideRestApi(retrofit: Retrofit): RestApi = retrofit.create(RestApi::class.java) |
| 64 | + |
| 65 | + @Provides |
| 66 | + @Singleton |
| 67 | + fun provideRestClient(restApi: RestApi): RestClient = RestClient(restApi) |
| 68 | + |
| 69 | + @Provides |
| 70 | + @Singleton |
| 71 | + fun provideWebService(restClient: RestClient): WebService = restClient |
| 72 | + |
| 73 | +} |
0 commit comments