0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Androidでmapを使った簡易cacheを作成する

Last updated at Posted at 2024-02-01

背景

Androidでサーバへ何度も問い合わせ必要の無い値や、app起動後しばらく同じ値を使いまわしたい時、値を保持しておくためのRepositoryが欲しくなったというシーンがあり、お試しで作ってみました。(なお本導入には至ってはおらず)

実践

開発環境や構成によってインタフェースがあったりDIがあったりと制約が多少はあるかもしれませんがお手軽にmapを使ってcacheするクラスを作成してみました。

/**
 * 簡易的なcache クラス.
 *
 * @author st-miz
 */
class CacheRepository {
    companion object {
        // defaultは5分cacheする想定
        private const val EXPIRED_TIME_MINUTES = 5L
    }

    private val cacheMap = mutableMapOf<String, CacheValue>()

    fun <T : Any> load(key: String): T? {
        cacheMap[key]?.let {
            if (it.expired()) {
                cacheMap.remove(key)
                return null
            } else {
                return it.data as? T
            }
        }
        return null
    }

    fun <T : Any> save(key: String, data: T, expiredMinutes: Long = EXPIRED_TIME_MINUTES) {
        cacheMap[key] = CacheValue(
            data = data,
            expiredMinutes = expiredMinutes,
        )
    }

    fun remove(key: String) {
        cacheMap.remove(key)
    }

    fun clear() {
        cacheMap.clear()
    }

    private data class CacheValue(
        val data: Any,
        private val expiredMinutes: Long,
    ) {
        private val expired: LocalDateTime = LocalDateTime.now().plusMinutes(expiredMinutes)
        fun expired(): Boolean {
            return LocalDateTime.now() > expired
        }
    }
}

感想

map使ってもいいんですが、普通にLruCacheとかでいい気がしてきたのでそのうち別記事を書くかもしれない。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?