在官方应用程序架构指南中是存储库的一个例子。检查数据库中是否存在对象以及是否新鲜:
// check if user was fetched recently
boolean userExists = userDao.hasUser(FRESH_TIMEOUT);
任何想法如何为 DAO 实现该功能(hasUser)?
在官方应用程序架构指南中是存储库的一个例子。检查数据库中是否存在对象以及是否新鲜:
// check if user was fetched recently
boolean userExists = userDao.hasUser(FRESH_TIMEOUT);
任何想法如何为 DAO 实现该功能(hasUser)?
您应该在表格中添加一个额外的字段,例如COLUMN_LAST_FETCHED
日期,并且在每次询问后,使用时间戳更新该字段。
考虑使用android-architecture-components GitHub项目中RateLimiter
所示的类来检查数据是否最近被获取:
@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.
}