Search code examples
androidkotlinandroid-sqliteandroid-roomandroid-database

Why can't I use suspend modifier in dao's @Insert in room database?


When I use the @Insert function in DAO, the following error occurs.

error: Type of the parameter must be a class annotated with @Entity or a collection/array of it.

All other codes using Room use suspend in @Insert, so I don't know the cause of the error.

Then I just deleted suspend and it works normally.

For what reason?


gradle

def room_version = "2.4.2"

implementation "androidx.room:room-runtime:$room_version"
implementation "androidx.room:room-ktx:$room_version"
kapt "androidx.room:room-compiler:$room_version"

Entity

@Entity
data class DailyWorkout(
    @PrimaryKey(autoGenerate = true)
    val id : Int = 0,
    val date: String,
    val bodyPart: String, // bodyPart
)

DAO

@Dao
interface WorkoutDao {
    @Query("SELECT * From WorkoutList")
    fun getWorkoutList() : List<WorkoutList>

    @Insert
    fun insertDailyLog(dailyWorkout: DailyWorkout)
}

Repostiory

class WorkoutListRepository(private val dao: WorkoutDao) {

    @RequiresApi(Build.VERSION_CODES.O)
    fun createDailyLog(part: BodyPart) {
        val date = LocalDate.now()
        val formatter =
            DateTimeFormatter
                .ofPattern("yyyy/M/dd E")
                .format(date)

        val data = DailyWorkout(date = formatter, bodyPart = part.getPart())
        dao.insertDailyLog(data)
    }
}

ViewModel

class WorkoutListViewModel(
    private val repository: WorkoutListRepository

) : ViewModel() {
    private var _list = MutableLiveData<List<String>>()
    val list: LiveData<List<String>>
        get() = _list

    @RequiresApi(Build.VERSION_CODES.O)
    fun createDailyLog(part: BodyPart) {
        viewModelScope.launch(Dispatchers.IO) {
            repository.createDailyLog(part)
        }
    }
}

Solution

  • Try updating the gradle dependencies:

    implementation "androidx.room:room-runtime:2.5.0-alpha02"
    implementation "androidx.room:room-ktx:2.5.0-alpha02"
    kapt "androidx.room:room-compiler:2.5.0-alpha02"