How to use suspend function on Room Db?

Related searches

I am using Room Db using coroutines in kotlin. This is my Dao interface:

@Dao
interface CheckListNameDao {

    @Insert
    suspend fun insertName(name: CheckListName)


    @Query("SELECT * FROM CheckListNamesTable")
    fun getAllNames(): LiveData<List<CheckListName>>
}

getAllNames() method works fine. The problem is with the insertName() method. When I remove the suspend keyword from the insertName() method, it throws this exception: java.lang.IllegalStateException: Cannot access database on the main thread since it may potentially lock the UI for a long period of time. But, when I use suspend keyword, I cannot build the project anymore. It shows the following error:

error: Methods annotated with @Insert can return either void, long, Long, long[], Long[] or List<Long>.
public abstract java.lang.Object insertName(@org.jetbrains.annotations.NotNull()

Why this error is showing? My code is based on this Android Room with a View - Kotlin

Edit: This is my repository:

class MainRepository(application: Application) {

        private var nameDao: CheckListNameDao = AppDatabase.getDatabase(application.applicationContext)
                .checkListNameDao()

        fun getAllNames(): LiveData<List<CheckListName>> {
            return nameDao.getAllNames()
        }

        suspend fun setNewListName(checkListName: CheckListName) {
            nameDao.insertName(checkListName)
        }
    }

This is the viewmodel:

class MainViewModel(application: Application) : AndroidViewModel(application) {

    private var mainRepository = MainRepository(application)

    fun getAllNames(): LiveData<List<CheckListName>> {
        return mainRepository.getAllNames()
    }

    fun setNewListName(name: String) {
        viewModelScope.launch {
            mainRepository.setNewListName(CheckListName(0, name))
        }
    }
}

EDIT 2:

I am also getting this error when I add the suspend keyword:

error: Type of the parameter must be a class annotated with @Entity or a collection/array of it.
kotlin.coroutines.Continuation<? super kotlin.Unit> p1);

This is the CheckListName data class:

@Entity(tableName = "CheckListNamesTable")
data class CheckListName(

        @PrimaryKey(autoGenerate = true)
        var id: Int,

        var name: String
)

As per the Room Declaring Dependencies documentation, you need a dependency on room-ktx to use Coroutines and, with that, suspend methods:

implementation "androidx.room:room-ktx:2.2.3"

How to use suspend function on Room Db?, As per the Room Declaring Dependencies documentation, you need a dependency on room-ktx to use Coroutines and, with that, suspend� In our suspend function implementation, the same logic from the synchronous insert method is wrapped in a `Callable`. Room calls the `CoroutinesRoom.execute` suspend function, which switches to a

The following code snippet contains a sample database configuration with one entity and one DAO:

@Entity
data class User(
    @PrimaryKey val uid: Int,
    @ColumnInfo(name = "first_name") val CheckListName: String?,
)

Coroutines With Room Persistence Library, To implement click handlers that trigger database operations, follow this pattern: Launch a coroutine that runs on the main or UI thread, because the result affects the UI. Call a suspend function to do the long-running work, so that you don't block the UI thread while waiting for the result. Implement suspension functions on Data Access Objects (or DAO) in Room. Call them using Kotlin’s coroutines for database transactions. As you progress, you’ll take an app listing the top 20 tennis players and refactor it to use suspension functions and coroutines.

Add the suspend keyword modifier to your Dao class methods in order to use suspension.

    @Dao
    interface TaskDao {
        @Insert(onConflict = OnConflictStrategy.REPLACE)
        suspend fun insertTask(t: Task): Long
        @Query(value = "SELECT * FROM tasks")
        suspend fun tasks(): List<Task>
        @Update
        suspend fun updateTask(t: Task)
        @Delete
        suspend fun deleteTask(t: Task)
    }

Along with @Insert, @Update, and @Delete, the @Query annotation method also supports the suspend keyword. After adding the suspension, our Dao class methods can execute without blocking the current thread. Use the below link for reference-

how to use suspend in Room database

Android Kotlin Fundamentals: Coroutines and Room, I'm trying to make all database query / delete functions in the Dao class as suspend functions. I enabled kotlin coroutine in gradle, and add� Next, add the suspend keyword modifier to your Dao class methods in order to use suspension. @Dao interface TaskDao { @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insertTask(t: Task): Long @Query(value = "SELECT * FROM tasks") suspend fun tasks(): List<Task> @Update suspend fun updateTask(t: Task) @Delete suspend fun deleteTask(t: Task) }

Error when use suspend function with room dao methods � Issue , The Android Architecture Component library Room Persistence Next, add the suspend keyword modifier to your Dao class methods in order to use Testing a Dao suspending method is not different from other function. A suspend function can be used as a regular function, and it will suspend the execution of the coroutine. For example, delay () is a built-in suspending function. Thank Android Studio for the

Kotlin Coroutines And Android Room With Suspend Keyword, The following example demonstrates it by measuring the total time it takes to execute both suspending functions: import kotlinx.coroutines.* import kotlin.system.* fun main () = runBlocking<Unit> { //sampleStart val time = measureTimeMillis { val one = doSomethingUsefulOne () val two = doSomethingUsefulTwo () println ("The answer is $ {one + two}") } println ("Completed in $time ms") //sampleEnd } suspend fun doSomethingUsefulOne (): Int { delay (1000L) // pretend we are doing something

To continue the coroutines integration, we're going to use the support for suspend functions in the stable version of Room and Retrofit, then simplify the code we just wrote substantially by using

Comments
  • Can you share the code from where you have call insertName method?
  • @KishanMaurya i have added repository and view model classes
  • As per error, the insert should have a return type. @Insert suspend fun insertName(name: CheckListName):Long now handle this in viewmodel
  • @KishanMaurya I have added a Long return type and the error still shows up.
  • @KishanMaurya i have edited the question again.
  • What version of Room are you using?
  • i am using version 2.2.3
  • thats exactly what I did.