Open In App

Room Database with Kotlin Coroutines in Android

Last Updated : 28 Jan, 2022
Improve
Improve
Like Article
Like
Save
Share
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.2.4"
kapt "androidx.room:room-compiler:2.2.4"
implementation "androidx.room:room-ktx:2.2.5"

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

apply plugin: 'kotlin-kapt'

Create the entity that will be our data class in 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
            }
        }
    }




Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads