【发布时间】:2020-03-30 00:55:51
【问题描述】:
我正在尝试使用带有暂停关键字的房间数据库。
我可以成功地将数据插入到数据库中。但是在那之后,insert方法不会返回任何东西,这意味着插入后我不能做任何事情,例如通过返回的id插入另一个数据。
这是我的示例代码:
@Dao
interface EventDao {
...
@Insert
suspend fun insert(event: Event): Long
...
}
class EventRepository(...) {
...
suspend fun insertEvent(event: Event, personId: Long) {
val id = eventDao.insertSync(event)
// !!! FREEZE - the code below here will never reach !!!
val attendee = EventAttendee(
personId = personId,
eventId = id
)
eventAttendeeDao.insert(attendee)
}
...
}
class EventEditingViewModel(...) : ViewModel() {
...
fun addEvent(event: Event) {
event.userId = userId
viewModelScope.launch {
eventRepository.insertEvent(event, friendId)
}
}
...
}
实际上,如果我删除suspend 关键字,我可以正确获取返回ID。只有当我在 Dao 类的插入方法前使用suspend关键字时才会出现冻结问题。
Logcat 没有显示任何日志,应用程序也没有崩溃,所以我不知道发生了什么。
我的房间版本是2.2.1。我也试过2.2.2。
我在房间数据库中使用挂起功能的方法有误吗?
【问题讨论】:
标签: android android-room kotlin-coroutines