Room helps you save and read data on your phone easily. Coroutines let you do this work without freezing the app.
0
0
Room with Coroutines in Android Kotlin
Introduction
You want to save user notes locally and load them smoothly.
You need to fetch a list of saved items without making the app slow.
You want to update or delete data in the background while the user uses the app.
You want to keep your app responsive when working with a database.
Syntax
Android Kotlin
@Dao
interface YourDao {
@Query("SELECT * FROM your_table")
suspend fun getAllItems(): List<YourEntity>
@Insert
suspend fun insertItem(item: YourEntity)
@Delete
suspend fun deleteItem(item: YourEntity)
}suspend means the function works with coroutines and runs without blocking the app.
Use @Query, @Insert, and @Delete annotations to tell Room what to do.
Examples
This gets all users from the database without freezing the app.
Android Kotlin
@Dao
interface UserDao {
@Query("SELECT * FROM users")
suspend fun getUsers(): List<User>
}This adds a new user to the database in the background.
Android Kotlin
@Dao
interface UserDao {
@Insert
suspend fun addUser(user: User)
}This deletes a user from the database smoothly.
Android Kotlin
@Dao
interface UserDao {
@Delete
suspend fun removeUser(user: User)
}Sample App
This example shows how to create a simple Room database with a User table. It adds two users and then prints them using coroutines to keep the app smooth.
Android Kotlin
import androidx.room.* import kotlinx.coroutines.* @Entity(tableName = "users") data class User( @PrimaryKey val id: Int, val name: String ) @Dao interface UserDao { @Query("SELECT * FROM users") suspend fun getUsers(): List<User> @Insert suspend fun addUser(user: User) } @Database(entities = [User::class], version = 1) abstract class AppDatabase : RoomDatabase() { abstract fun userDao(): UserDao } fun main() = runBlocking { val db = Room.inMemoryDatabaseBuilder( context = androidx.test.core.app.ApplicationProvider.getApplicationContext(), AppDatabase::class.java ).build() val userDao = db.userDao() launch { userDao.addUser(User(1, "Alice")) userDao.addUser(User(2, "Bob")) val users = userDao.getUsers() users.forEach { println("User: ${it.id} - ${it.name}") } } }
OutputSuccess
Important Notes
Always call Room database functions from coroutines or background threads to avoid freezing the app.
Use suspend functions in your DAO to work nicely with coroutines.
Room handles database operations safely and efficiently when combined with coroutines.
Summary
Room stores data on the device using simple code.
Coroutines let Room work without stopping the app from running.
Use suspend functions in DAO to run queries smoothly.