前言
在上一篇Room我们了解如何简单的使用Room数据库https://blog.csdn.net/csdn546229768/article/details/116569028点我跳转
那么这篇将使用Viewmode管理数据Activity层只负责处理view
一、ViewModel是什么?
- ViewModel是一个类,负责准备和管理Activity或的数据Fragment。它还处理活动/片段与应用程序其余部分的通信(例如,调用业务逻辑类)。
- ViewModel通常通过LiveData或Android数据绑定公开此信息。
- ViewModel的唯一责任是管理UI的数据。它永远不应访问您的视图层次结构,也不应保留对活动或片段的引用。
二、使用步骤
(这里讲Room和ViewMode的结合使用所以不讲ViewMode的使用了)
1. 引入库
在上篇的代码基础上进行添加
//viewModeScope
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:2.3.1"
2. 新建ViewMode类
-
首先集成AndroidViewModel–为什么是AndroidViewModel因为比ViewModel好用
-
将room数据库配置信息声明成域
private val wordDatabase by lazy {
Room.databaseBuilder(
application,
WordDataBases::class.java,
"word_database.db"
)
.build()
} //配置Dabase信息
private val wordDao by lazy { wordDatabase.getWordDao() } //获取Dao层控制对象
3. 将room数据库配置信息声明成域
fun getAllWords() = wordDao.getAllWords() //获取全部数据
fun insertView(){
viewModelScope.launch { //这里为什么没有换线程 ----因为我在insertWords这个方法声明了suspend函数
wordDao.insertWords(Emp(null, "Hello", "你好"))
}
}
fun clearView() {
viewModelScope.launch {
withContext(Dispatchers.Default) {
wordDao.clearAll()
}
}
}
fun deleteView() {
viewModelScope.launch {
withContext(Dispatchers.Default) {
wordDao.deleteWords(Emp(1, null, null))//删除id为1的
}
}
}
fun updateView() {
viewModelScope.launch {
withContext(Dispatchers.Default) {
wordDao.updateWords(Emp(7, "update", "修改了"))
}
}
}
- 总和代码WordViewMode.kt
import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.viewModelScope
import androidx.room.Room
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import net.sourceforge.room_demo.dao.WordDataBases
import net.sourceforge.room_demo.emp.Emp
/**
@author 杨景
@description:
@date : 2021/5/10 0010 15:05
*/
class WordViewMode(application: Application) : AndroidViewModel(application){
private val wordDatabase by lazy {
Room.databaseBuilder(
application,
WordDataBases::class.java,
"word_database.db"
)
.build()
} //配置Dabase信息
private val wordDao by lazy { wordDatabase.getWordDao() } //获取Dao层控制对象
fun getAllWords() = wordDao.getAllWords() //获取全部数据
fun insertView(){
viewModelScope.launch { //这里为什么没有换线程 ----因为我在insertWords这个方法声明了suspend函数
wordDao.insertWords(Emp(null, "Hello", "你好"))
}
}
fun clearView() {
viewModelScope.launch {
withContext(Dispatchers.Default) {
wordDao.clearAll()
}
}
}
fun deleteView() {
viewModelScope.launch {
withContext(Dispatchers.Default) {
wordDao.deleteWords(Emp(1, null, null))//删除id为1的
}
}
}
fun updateView() {
viewModelScope.launch {
withContext(Dispatchers.Default) {
wordDao.updateWords(Emp(7, "update", "修改了"))
}
}
}
}
4. WordDao层
import androidx.room.*
import kotlinx.coroutines.flow.Flow
import net.sourceforge.room_demo.emp.Emp
@Dao //用于访问数据库的方法。
interface WordDao {
@Insert(onConflict = OnConflictStrategy.REPLACE) //如果有冲突就直接代替
suspend fun insertWords( emp: Emp):Long
@Update
fun updateWords(emp: Emp):Int
@Delete
fun deleteWords(emp: Emp):Int
@Query("SELECT * FROM EMP ORDER BY ID DESC")
fun getAllWords():Flow<MutableList<Emp>> //使用room-ktx包下
@Query("DELETE FROM EMP")
fun clearAll():Int
}
5. Activity层进行使用
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelProviders
import androidx.lifecycle.lifecycleScope
import androidx.room.Room
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.InternalCoroutinesApi
import kotlinx.coroutines.flow.FlowCollector
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import net.sourceforge.room_demo.dao.WordDataBases
import net.sourceforge.room_demo.emp.Emp
/*
* 在数据库中 删除某一行数据 id是不会重新排序的 比如删除了id=10 那么就没有10了
*
* */
class MainActivity : AppCompatActivity() {
private val wordViewMode by lazy {
ViewModelProviders.of(this).get(WordViewMode::class.java)
}
@InternalCoroutinesApi //标记协程内部的声明
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//获取全部数据
val allWords = wordViewMode.getAllWords()
//对Fow数据进行监听
lifecycleScope.launch(Dispatchers.Default) {
allWords.collect(object : FlowCollector<MutableList<Emp>> {
override suspend fun emit(value: MutableList<Emp>) {
val text = StringBuffer()
value.forEach {
text.append("id:${it.id} , ${it.word} = ${it.chineseMeaning}\n")
}
withContext(Dispatchers.Main) { textview.text = text }
}
})
}
bt_insert.setOnClickListener { wordViewMode.insertView() } //插入数据 }
bt_update.setOnClickListener { wordViewMode.updateView() }
bt_delete.setOnClickListener { wordViewMode.deleteView() }
bt_clear.setOnClickListener { wordViewMode.clearView() }
}
}
- 这里对room-ktx扩展包的使用 Flow<> 可以简单理解为LiveData可以对集合数据进行监听
- suspend 关键字进行协程声明
完结
与ViewModel的结合就到这里了
需要完整代码的下方评论邮箱,下一章讲Room数据库结构的改变