룬아님의 취중코딩

GitHub API를 사용하는 기본적인 Retrofit과 Koin 조합 본문

개발/안드로이드 개발

GitHub API를 사용하는 기본적인 Retrofit과 Koin 조합

룬아님 2019. 10. 31. 14:19
interface GitHubAPI {

    @GET("/search/repositories")
    suspend fun searchRepositories(@Query("q") searchKeyWord: String): RepositoriesResponse

    @GET("repos/{repoUrl}")
    suspend fun getRepositoryInfo(@Path("repoUrl", encoded = true) repoUrl: String): Repository

    @GET("users/{id}")
    suspend fun getUserInfo(@Path("id") userUrl: String): Owner

}​

 

private const val BASE_URL = "https://api.github.com"
private const val CONNECT_TIMEOUT = 15L
private const val WRITE_TIMEOUT = 15L
private const val READ_TIMEOUT = 15L

val NetworkModule = module {
    single { Cache(androidApplication().cacheDir, 10L * 1024 * 1024) }

    single {
        Interceptor { chain ->
            chain.proceed(chain.request().newBuilder().apply {
                header("Accept", "application/vnd.github.mercy-preview+json")
            }.build())
        }
    }

    single {
        OkHttpClient.Builder().apply {
            cache(get())
            connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)
            writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS)
            readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)
            retryOnConnectionFailure(true)
            addInterceptor(get())
            addInterceptor(HttpLoggingInterceptor().apply {
                if (BuildConfig.DEBUG) {
                    level = HttpLoggingInterceptor.Level.BODY
                }
            })
        }.build()
    }

    single { GsonBuilder().create() }

    single {
        Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create(get()))
            .addCallAdapterFactory(CoroutineCallAdapterFactory())
            .client(get())
            .build()
    }
}

 

val ApiModule = module {
    single<GitHubAPI>(createdAtStart = false) { get<Retrofit>().create(GitHubAPI::class.java) }
}
반응형
Comments