implement runtime cache for Crunchyroll.browse()

This commit is contained in:
Jannik 2022-04-16 17:52:10 +02:00
parent 1ebc1194e6
commit 7d6c300f7e
Signed by: Seil0
GPG Key ID: E8459F3723C52C24
1 changed files with 22 additions and 11 deletions

View File

@ -67,7 +67,7 @@ object Crunchyroll {
private var signature = ""
private var keyPairID = ""
private val browsingCache = arrayListOf<Item>()
private val browsingCache = hashMapOf<String, BrowseResult>()
/**
* Load the pai token, see:
@ -286,18 +286,29 @@ object Crunchyroll {
parameters.add("categories" to categories.joinToString(",") { it.str })
}
val browseResult: BrowseResult = try {
requestGet(browseEndpoint, parameters)
}catch (ex: SerializationException) {
Log.e(TAG, "SerializationException in browse().", ex)
NoneBrowseResult
// fetch result if not already cached
if (browsingCache.contains(parameters.toString())) {
Log.d(TAG, "browse result cached: $parameters")
} else {
Log.d(TAG, "browse result not cached, fetching: $parameters")
val browseResult: BrowseResult = try {
requestGet(browseEndpoint, parameters)
}catch (ex: SerializationException) {
Log.e(TAG, "SerializationException in browse().", ex)
NoneBrowseResult
}
// if the cache has more than 100 entries clear it, so it doesn't become a memory problem
// Note: this value is totally guessed and should be replaced by a properly researched value
if (browsingCache.size > 100) {
browsingCache.clear()
}
// add results to cache
browsingCache[parameters.toString()] = browseResult
}
// add results to cache TODO improve
browsingCache.clear()
browsingCache.addAll(browseResult.items)
return browseResult
return browsingCache[parameters.toString()] ?: NoneBrowseResult
}
/**