In one of my project, there are some tables, and we save the id value of one table on another table, for example, we have album information, which has albumId and albumName fields, and on another table episode, it contain the albumId value, so when I query episode, I also want to get the albumName, and most of the albumId is the same.
My original implementation is like below:
val episodeList = getEpisodeList().map{
it.copy(albumName = getAlbumName(it.albumId))
}
The method getEpisodeList will query database, and get method getAlbumName will also query the database, and the map method will iterate all the episode to get the albumName, even the albumId is the same, it will query multiple times. I created a class CachedMap to solve the problem.
My implementation is like below:
class CachedMap<K, V>(val funGetValue: (key: K) -> V) {
val cache = mutableMapOf<K, V>()
fun getCachedValue(key: K): V {
cache[key]?.let {
Napier.d("Get value from cache", tag = "CachedMap")
return it
}
val value = funGetValue(key)
cache[key] = value
return value
}
}
With CachedMap, the implementation is like below:
val albumNameCache = CachedMap<Long?, String> { getAlbumName(it) ?: "" }
val episodeList = getEpisodeList().map{
it.copy(albumName = albumNameCache.getCachedValue(it.albumId)
}