从概念上讲,如何使用 LiveData 和 Room 执行简单的读取/更新周期?



在存储库类中(请参阅:https://developer.android.com/jetpack/docs/guide),我正在尝试:

1) 从房间 DB 中读取值

2) 递增值

3)通过appDao将值写回房间。

我很确定我可以在 Dao 级别解决这个问题,即在交易或其他方面,但我不确定这是否是正确的方法。 这似乎是一个非常简单的用例,我想出的解决方案似乎比必要的要复杂得多。 我想知道我对 Kotlin 协程的脆弱处理是否阻碍了我。


/* Repository Class*/
fun getCurrentAlarmTime():LiveData<Calendar> {
return Transformations.map(appDao.getProfileData(currentAlarmTime)){ nullableProfileData ->
if (nullableProfileData == null) {
defaultAlarmTime
} else {
nullableProfileData.value.toLongOrNull()?.let { millis ->
getCalendar(millis)
}
}
}
}
fun setCurrentAlarmTime(calendar:Calendar) {
GlobalScope.launch {
appDao.setProfileData(
ProfileData(
currentAlarmTime,
calendar.timeInMillis.toString()
)
)
}
}
fun incrementAlarmTimeBy1Hour() {
// this is what I'm having a problem with, using the fns above.
// I've got a pretty good handle on LiveData, 
// Transformations, and MediatorLiveData, 
// but I am still stuck.
}
Expected result would be that the time in the database is updated by 1 hour.

我想我想出了一些不是一个糟糕的解决方案,通过阅读这里的 Room 参考资料:https://developer.android.com/training/data-storage/room/accessing-data

关键在于 Room 可以返回 LiveData,或者它可以返回我称之为同步查询的内容。 这是以下两个签名之间的区别:

@Query("SELECT * FROM profileData WHERE entry = :entry limit 1")
fun getProfileData(entry: String): LiveData<ProfileData?>
@Query("SELECT * FROM profileData WHERE entry = :entry limit 1")
suspend fun getProfileDataSync(entry: String): ProfileData

第一个您将观察,第二个您可以直接从协程调用。

如果这不是最佳实践,有人应该让我知道,但上面的参考资料似乎支持它。

需要注意的是,我不必将房间数据库置于任何奇怪的同步模式来支持这一点。

最新更新