📜  Android 中带有 Kotlin 协程的房间数据库

📅  最后修改于: 2022-05-13 01:58:44.846000             🧑  作者: Mango

Android 中带有 Kotlin 协程的房间数据库

该项目将用于实施阶段。如果您还没有完成项目,您应该完成然后返回。为了简单起见,该项目采用了基本的 MVVM 架构。本博客中提到的实现的完整代码可以在项目本身中找到。首先,我们必须配置 Room Database 的依赖项,如下所示:

implementation "androidx.room:room-runtime:2.2.4"
kapt "androidx.room:room-compiler:2.2.4"
implementation "androidx.room:room-ktx:2.2.5"

不要忘记在您的应用级 gradle 文件中包含 Kotlin Annotation Processing 插件。

apply plugin: 'kotlin-kapt'

在 Room Database 中创建将成为我们的数据类的实体,例如 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?
)


Kotlin
@Dao
interface CourseDao {
  
    @Query("SELECT * FROM Course")
    suspend fun getAll(): List
    
    @Insert
    suspend fun insertAll(Courses: List)
      
    @Delete
    suspend fun delete(Course: Course)
      
}


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


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()
}


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


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
            }
        }
    }


对于这个用户,我们必须创建 Room Database 所需的 Dao,我们将其称为 CourseDao。

科特林

@Dao
interface CourseDao {
  
    @Query("SELECT * FROM Course")
    suspend fun getAll(): List
    
    @Insert
    suspend fun insertAll(Courses: List)
      
    @Delete
    suspend fun delete(Course: Course)
      
}

请记住,我们使用了暂停关键字来支持协程,因此我们可以从协程或其他挂起函数中调用它。我们现在必须创建将扩展 RoomDatabase 的 AppDatabase。

科特林

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

之后,我们将需要一个单例的 DatabaseBuilder。

科特林

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()
}

然后,我们将使 DatabaseHelperImpl 实现 DatabaseHelper。

科特林

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

同样,我们使用了暂停函数,以便我们可以从协程或另一个暂停函数中调用它。我们可以将这个实例传递到任何需要它的地方,例如 ViewModel,并进行查询以从数据库中获取用户,如下所示

科特林

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
            }
        }
    }