首页 > 解决方案 > 房间返回 LiveData 后,检查是否需要更新

问题描述

如标题所述,我有 Room Database 将 LiveData 返回到 Repository 的场景。Repository 对 ViewModel 做同样的事情:

suspend fun getData(key: Long): LiveData<CustomData> = withContext(Dispatchers.IO) {
    return@withContext myDao.getDataByKey(key)
}

ViewModel 从 switchMap 获取数据:

val data = anotherValue.switchMap { key ->
    liveData {
        emitSource(repository.getData(key))
    }
}

那行得通。但是现在我想,一旦返回数据,或者就在之前,检查该数据是否足够旧以检查新数据(改造)。

我知道如何从服务中获取它,但找不到如何正确启动该更新。如果我检查存储库中的数据,在将其发送到 ViewModel 之前,从 DAO 返回的值始终为空。而且从 ViewModel 中,无法弄清楚该怎么做。

另一种选择可能是从片段中进行,因为我已经在观察 LiveData。但是希望尽可能保持清洁,而且我认为这不是一个好习惯。

标签: androidrepositoryandroid-roomviewmodelandroid-livedata

解决方案


推荐阅读