VOOZH about

URL: https://www.geeksforgeeks.org/android/room-database-with-kotlin-coroutines-in-android/

⇱ Room Database with Kotlin Coroutines in Android - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Room Database with Kotlin Coroutines in Android

Last Updated : 12 Jun, 2024

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.


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


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.


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


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


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

Comment
Article Tags:
Article Tags:

Explore