Android 从概念上讲,如何使用LiveData和Room进行简单的读取/更新循环?
在存储库类中,请参见:,我正在尝试: 1从房间数据库中读取一个值 2增加值 3通过appDao将值写回房间 我很确定我可以在Dao级别解决这个问题,例如在事务或其他方面,但我不确定这是否是正确的方法。这似乎是一个非常简单的用例,我提出的解决方案似乎比必要的复杂得多。我想知道我对科特林合作项目的脆弱控制是否让我回到这里Android 从概念上讲,如何使用LiveData和Room进行简单的读取/更新循环?,android,kotlin,Android,Kotlin,在存储库类中,请参见:,我正在尝试: 1从房间数据库中读取一个值 2增加值 3通过appDao将值写回房间 我很确定我可以在Dao级别解决这个问题,例如在事务或其他方面,但我不确定这是否是正确的方法。这似乎是一个非常简单的用例,我提出的解决方案似乎比必要的复杂得多。我想知道我对科特林合作项目的脆弱控制是否让我回到这里 /* Repository Class*/ fun getCurrentAlarmTime():LiveData<Calendar> { retur
/* 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可以返回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
第一个是你观察到的,第二个是你可以直接从协同程序中调用的
如果这不是最佳实践,应该有人告诉我,但上面的参考资料似乎支持这一点
需要注意的是,我不必将房间数据库置于任何奇怪的同步模式来支持这一点。我喜欢将第一个变量调用为getXxxxWithChanges,将第二个变量调用为getXxxx。我觉得挂起并不是真正的同步。