房间 - 检查最近是否提取数据

时间:2018-06-18 12:10:50

标签: android dao android-room android-architecture-components android-jetpack

官方Guide to App Architecture是存储库的一个例子。检查一个对象是否存在于数据库中,如果是新的:

// check if user was fetched recently
boolean userExists = userDao.hasUser(FRESH_TIMEOUT);

如何为DAO实现该功能( hasUser )?

3 个答案:

答案 0 :(得分:5)

大多数架构组件示例都可用here。 在您的情况下,我无法找到UserDao类,但有一个数据库架构示例hereDECLARE @xml AS XML, @hDoc AS INT, @sql NVARCHAR (MAX) SELECT @xml = xmlData FROM fxRatesXml EXEC sp_xml_preparedocument @hDoc OUTPUT, @xml, '<root xmlns:gesmes="http://www.gesmes.org/xml/2002-08-01" xmlns="http://www.ecb.int/vocabulary/2002-08-01/eurofxref"/>' SELECT * FROM OPENXML(@hDoc, 'gesmes:Cube') WITH ( [time] nvarchar(max) 'Cube/time', currency nvarchar(max) 'Cube/Cube/currency', rate nvarchar(max) 'Cube/Cube/rate' ) EXEC sp_xml_removedocument @hDoc 表格有一个users列。所以你可以这样写UserDao:

last_update

如果标识为@Query("SELECT COUNT(*) FROM users WHERE userId == :userId AND last_update >= :timeout) int hasUser(int userId, long timeout) 的用户不够新鲜,则返回0。

答案 1 :(得分:1)

您应该在表格中添加一个额外的字段,例如带有日期的COLUMN_LAST_FETCHED,并在每次审讯后,使用时间戳更新该字段。

答案 2 :(得分:0)

考虑使用android-architecture-components RateLimiter中的here类,如GitHub project所示,以一种非持久方式检查数据是否为最近获取的:

@Singleton 
@OpenForTesting 
class RepoRepository @Inject constructor(
    private val appExecutors: AppExecutors,
    private val db: GithubDb,
    private val repoDao: RepoDao,
    private val githubService: GithubService ) {

    private val repoListRateLimit = RateLimiter<String>(10, TimeUnit.MINUTES)

    fun loadRepos(owner: String): LiveData<Resource<List<Repo>>> {
        return object : NetworkBoundResource<List<Repo>, List<Repo>>(appExecutors) {
            override fun saveCallResult(item: List<Repo>) {
                repoDao.insertRepos(item)
            }

            override fun shouldFetch(data: List<Repo>?): Boolean {
                return data == null || data.isEmpty() || repoListRateLimit.shouldFetch(owner)
            }

            override fun loadFromDb() = repoDao.loadRepositories(owner)

            override fun createCall() = githubService.getRepos(owner)

            override fun onFetchFailed() {
                repoListRateLimit.reset(owner)
            }
        }.asLiveData()
    }

    // Details omitted for brevity.
}