首页 > 解决方案 > 在 Kotlin 中构建自己的缓存

问题描述

我有一个包含四个元素的列表:created_at, text, name, screen_name。第一个代表创建日期,第二个代表推文的文本,最后一个代表用户的姓名和屏幕名称。我想用寿命来存储这些信息,一个随机的寿命。为此,我考虑使用缓存和此链接的实现https://medium.com/@kezhenxu94/how-to-build-your-own-cache-in-kotlin-1b0e86005591

我的问题是:

请给我一个示例来存储这些数据。或者,如果有另一种方法可以更正确地制作我想要的东西,请告诉我。

我现在的代码:

class ExpirableCache(private val delegate: Cache, private val flushInterval: Long = TimeUnit.MINUTES.toMillis(1000)) : Cache {
    private val dataTweet: Map<Long, Long>? = null

    private var lastFlushTime = System.nanoTime()

    override val size: Int
        get() = delegate.size

    override fun set(key: Any, value: Any) {
        delegate[key] = value
    }

    override fun remove(key: Any): Any? {
        recycle()
        return delegate.remove(key)
    }

    override fun get(key: Any): Any? {
        recycle()
        return delegate[key]
    }

    override fun add(key: Any, value: Any) {
        dataTweet[0, value]
    }

    override fun clear() = delegate.clear()

    private fun recycle() {
        val shouldRecycle = System.nanoTime() - lastFlushTime >= TimeUnit.MILLISECONDS.toNanos(flushInterval)
        if (!shouldRecycle) return
        delegate.clear()
    }
}

标签: androidkotlincaching

解决方案


推荐阅读