Skip to content

Commit

Permalink
feat: cache network responses using OkHttp cache
Browse files Browse the repository at this point in the history
resolves #400
  • Loading branch information
David Ly committed Sep 2, 2023
1 parent fd55c6b commit 8fa0303
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 3 deletions.
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
package ly.david.data.di.network

import android.content.Context
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import io.ktor.client.HttpClient
import io.ktor.client.call.NoTransformationFoundException
Expand All @@ -14,6 +16,7 @@ import io.ktor.client.plugins.logging.Logging
import io.ktor.client.statement.bodyAsText
import io.ktor.http.HttpHeaders
import io.ktor.http.HttpStatusCode
import java.io.File
import javax.inject.Singleton
import ly.david.data.BuildConfig
import ly.david.data.core.network.ApiHttpClient
Expand All @@ -24,6 +27,7 @@ import ly.david.data.network.api.MusicBrainzApi
import ly.david.data.spotify.api.SpotifyApi
import ly.david.data.spotify.api.auth.SpotifyAuthApi
import ly.david.data.spotify.api.auth.SpotifyAuthState
import okhttp3.Cache
import timber.log.Timber

@Module
Expand All @@ -32,8 +36,15 @@ object NetworkModule {

@Singleton
@Provides
fun provideHttpClient(): HttpClient {
return ApiHttpClient.configAndCreate {
fun provideHttpClient(
@ApplicationContext context: Context,
): HttpClient {
return ApiHttpClient.configAndCreate(
cache = Cache(
directory = File(context.cacheDir, "ktor_okhttp_cache"),
maxSize = 50 * 1024 * 1024,
)
) {
HttpResponseValidator {
handleResponseExceptionWithRequest { exception, _ ->
handleRecoverableException(exception)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,22 @@ import io.ktor.client.engine.okhttp.OkHttp
import io.ktor.client.plugins.contentnegotiation.ContentNegotiation
import io.ktor.serialization.kotlinx.json.json
import kotlinx.serialization.json.Json
import okhttp3.Cache

object ApiHttpClient {
fun configAndCreate(block: HttpClientConfig<*>.() -> Unit): HttpClient {
fun configAndCreate(
cache: Cache,
block: HttpClientConfig<*>.() -> Unit,
): HttpClient {
return HttpClient(OkHttp) {
expectSuccess = true

engine {
config {
cache(cache)
}
}

install(ContentNegotiation) {
json(
Json {
Expand Down

0 comments on commit 8fa0303

Please sign in to comment.