I'm trying to use room database with suspend keyword.
I can successfully insert a data into database. But after that, the insert method will not return anything, that means I can't do anything after insertion such as insert another data by the returned id.
here is my sample code:
@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)
}
}
...
}
Actually, if I remove suspend keyword, I can get the return id properly. The freezing problem will only happen when I use suspend keyword in front of insertion method in Dao class.
Logcat doesn't show any logs of this, and the app doesn't crash, so I have no idea what happened.
My room version is 2.2.1. and I've tried 2.2.2 also.
Did I do the wrong way to use suspend function in room database?