Android Jetpack之ViewModel、LiveData
Android Jetpack之LifeCycle
前言
Jetpack是一个由多个技术库组成的套件,可帮助开发者遵循最佳做法,减少样板代码并编写可在各种Android版本和设备中一致运行的代码,让开发者精力集中编写重要的代码。
一、官方推荐的Jetpack架构
ViewModel是介于View(视图)和Model(数据模型)之间的中间层,能够使视图和数据分离,又能提供视图和数据之间的通信。
LiveData是一个能够在ViewModel中数据发生变化时通知页面刷新UI线程的组件库。
Room是在SQLLite上提供了一层封装。(Android采用SQLLite作为数据库存储)
二、添加依赖
implementation "androidx.activity:activity-ktx:1.2.0"implementation "androidx.fragment:fragment-ktx:1.3.0"
下面的案例,只是简洁的代码片段,大致介绍一下,让大家了解这个架构。具体详细代码及深度原理,请大家自行查阅其他深度讲解文章。
三、创建Repository
StudentRepository
class StudentRepository {var studentDao: StudentDao? = nullconstructor(context: Context) {val database = MyDatabase.getInstance(context)studentDao = database!!.getStudentDao()}//LiveData集合fun getAllStudentsLive(): LiveData<List<Student>> {return studentDao!!.getAllStudentsLive()}fun deleteAllStudents() {studentDao!!.deleteAllStudents()}fun queryAll(): List<Student>? {return studentDao!!.queryAll()}fun insertStudent(vararg student: Student?) {studentDao!!.insertStudent(*student)}fun deleteStudent(vararg student: Student) {studentDao!!.deleteStudent(*student)}fun updateStudent(vararg student: Student) {studentDao!!.updateStudent(*student)}}
StudentDao
@Daointerface StudentDao {@Insertfun insertStudent(vararg students: Student?)@Deletefun deleteStudent(vararg students: Student?)@Updatefun updateStudent(vararg students: Student?)@Query("SELECT * FROM student")fun getAllStudent(): List<Student?>?@Query("SELECT * FROM student WHERE id = :id")fun getStudentById(id: Int): List<Student?>?}
Repository
类中是关于Dao的操作,getAllStudentsLive()
方法返回的是一个LiveData集合。
四、创建ViewModel
StudentViewModel
class StudentViewModel(application: Application) : AndroidViewModel(application) {//初始化Repository对象private val repository by lazy { StudentRepository(application) } //定义LiveData集合private var liveDataStudent: LiveData<List<Student>>? = nullinit {liveDataStudent = repository.getAllStudentsLive()}fun getAllStudentsLive(): LiveData<List<Student>>? {viewModelScope.launch(Dispatchers.Default) {liveDataStudent = repository.getAllStudentsLive()}return liveDataStudent}private fun insertStudent(vararg student: Student) {viewModelScope.launch(Dispatchers.Default) {repository.insertStudent(*student)}}private fun deleteStudent(vararg student: Student) {viewModelScope.launch(Dispatchers.Default) {repository.deleteStudent(*student)}}private fun updateStudent(vararg student: Student) {viewModelScope.launch(Dispatchers.Default) {repository.updateStudent(*student)}}private fun deleteAllStudents() {viewModelScope.launch(Dispatchers.Default) {repository.deleteAllStudents()}}//以下为DataBinding布局调用的方法-------------------fun mInsert() {val s1 = Student("zhangsan", 26)val s2 = Student("lisi", 18)insertStudent(s1, s2)}fun mClear() {deleteAllStudents()}fun mDelete() {var s1 = Student(3)deleteStudent(s1)}fun mUpdate() {val s1 = Student(2, "wanger", 21)updateStudent(s1)}}
初始化数据库Repository,创建一个livedata集合的属性,并提供对其操作的方法。
五、activity中使用
mainActivity
class MainActivity : AppCompatActivity() {private var adapter: StudentRecyclerViewAdapter? = nullprivate var listStudent: ArrayList<Student> = ArrayList()private var viewModel: StudentViewModel? = nulloverride fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)//databindingval binding = DataBindingUtil.setContentView<ActivityMainBinding>(this, R.layout.activity_main)//viewmodelviewModel = ViewModelProvider(this)[StudentViewModel::class.java]binding.studentViewModel = viewModelbinding.lifecycleOwner = thisbinding.recycleView.layoutManager = LinearLayoutManager(this)adapter = StudentRecyclerViewAdapter(listStudent)binding.recycleView.adapter = adapter//livedata、roomviewModel!!.getAllStudentsLive()!!.observe(this,androidx.lifecycle.Observer {adapter!!.students = itadapter!!.notifyDataSetChanged()})}}
上面案例中,通过ActivityMainBinding获取对应控件,添加对应的逻辑,其次使用
getAllStudentsLive
方法获取到对应的LiveData,并通过observe
监听LiveData集合。