Open In App

Room Database with Kotlin Coroutines in Android

Last Updated : 12 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

This project will be used for the implementation phase. If you have not yet completed the project, you should do so and then return. To keep things simple, the project employs a basic MVVM architecture. The complete code for the implementation mentioned in this blog can be found in the project itself. First, we must configure the Room Database’s dependencies as shown below:

implementation("androidx.room:room-runtime:2.6.1")
kapt("androidx.room:room-compiler:2.6.1")
implementation("androidx.room:room-ktx:2.6.1")

Don’t forget to include the Kotlin Annotation Processing plugin in your app-level gradle file.

plugins {
... // Other plugins
id("kotlin-kapt")
}


Create the entity that will be our data class in the Room Database, for example, Course.

Kotlin
@Entity
data class GFG(
    @PrimaryKey val courseID: Int,
    @ColumnInfo(name = "courseName") val name: String?,
    @ColumnInfo(name = "courseID") val email: String?,
    @ColumnInfo(name = "coursePrice") val avatar: String?
)


For this User, we must create the Dao required for the Room Database, which we will call CourseDao.

Kotlin
@Dao
interface CourseDao {

    @Query("SELECT * FROM Course")
    suspend fun getAll(): List<Course>
  
    @Insert
    suspend fun insertAll(Courses: List<Course>)
    
    @Delete
    suspend fun delete(Course: Course)
    
}


Please keep in mind that we’ve used the suspend keyword to support Coroutines, so we can call it from a Coroutine or another suspend function. We must now create the AppDatabase that will extend RoomDatabase.

Kotlin
@Database(entities = [Course::class], version = 1)
abstract class AppDatabase : RoomDatabase() {
    abstract fun CourseDao(): CourseDao
}


Following that, we will require a DatabaseBuilder that is a Singleton.

Kotlin
object DatabaseBuilder {
    private var INSTANCE: GfgDatabase? = null
    fun getInstance(context: Context): GfgDatabase {
        if (INSTANCE == null) {
            synchronized(GfgDatabase::class) {
                INSTANCE = buildRoomDB(context)
            }
        }
        return INSTANCE!!
    }
    private fun buildRoomDB(context: Context) =
        Room.databaseBuilder(
            context.applicationContext,
            GfgDatabase::class.java,
            "geeksforgeeks-example-coroutines"
        ).build()
}


Then, we’ll make a DatabaseHelperImpl implement the DatabaseHelper.

Kotlin
class DatabaseHelperImpl(private val gfgDatabase: GfgDatabase) : DatabaseHelper {
    override suspend fun getCourses(): List<Course> = gfgDatabase.CourseDao().getAll()
    override suspend fun insertAll(Courses: List<Course>) = gfgDatabase.CourseDao().insertAll(Courses)
}


Again, we used the suspend function so that we could call it from a coroutine or another suspend function. We can pass this instance wherever it is needed, such as to the ViewModel, and make the query to get the users from the database as shown below

Kotlin
class RoomDBViewModel(private val gfgApiHelper: GfgApiHelper, private val dbHelper: DatabaseHelper) :
    ViewModel() {
    
    init {
        fetchCourses()
    }

    private fun fetchCourses() {
        viewModelScope.launch {
            try {
              val CoursesFromDb = dbHelper.getCourses()
              // here you have your CoursesFromDb
            } catch (e: Exception) {
              // handler error
            }
        }
    }


Next Article
Article Tags :

Similar Reads