【发布时间】:2020-10-29 05:46:45
【问题描述】:
在使用 Livedata 和更新行时,我在房间数据库中使用 MVVM 架构模式,它会立即在 recylerview 中显示更改。
@Query("select * from lessons_table where course_id = :courseId")
fun getListLessonDb(courseId:Int):LiveData<List<LessonEntity>>
但我想在 mvvm 中使用 Rxjava 而不是 livedata 来显示数据和更改,但是当更新数据行时,它不会立即显示 recyclerview 中的更改。这是我的代码:
道
@Dao
interface LessonDao {
@Query("select * from lessons_table where course_id = :courseId")
fun getListLessonDbRx(courseId: Int): Single<List<LessonEntity>>
@Update
fun updateLessonRX(lessonEntity: LessonEntity): Completable
}
课程资料库
class LessonRepository(val application: Application) {
val lessonDao: LessonDao
init {
val db = ArabiAraghiTutorialDatabase.getDataBase(application)
lessonDao = db!!.lessonDao()
}
fun getListFromDb(courseId: Int): LiveData<List<LessonEntity>> {
val result: MutableLiveData<List<LessonEntity>> = MutableLiveData()
getObservable(courseId).observeOn(Schedulers.io())
.subscribeOn(AndroidSchedulers.mainThread())
.subscribe(object : SingleObserver<List<LessonEntity>> {
override fun onSuccess(t: List<LessonEntity>) {
result.postValue(t)
}
override fun onSubscribe(d: Disposable) {
}
override fun onError(e: Throwable) {
}
})
return result
}
fun getObservable(courseId: Int): Single<List<LessonEntity>> = lessonDao.getListLessonDbRx(courseId)
fun updateLessenDbRx(lessonEntity: LessonEntity) {
lessonDao.updateLessonRX(lessonEntity).observeOn(AndroidSchedulers.mainThread())
.observeOn(Schedulers.io()).subscribe(object : CompletableObserver {
override fun onComplete() {
}
override fun onSubscribe(d: Disposable) {
}
override fun onError(e: Throwable) {
}
})
}
}
视图模型
class LessonViewModel(application: Application):AndroidViewModel(application) {
private val lessonRepository=LessonRepository(application)
fun getListLessonFromDb(courseId: Int):LiveData<List<LessonEntity>> = lessonRepository.getListFromDb(courseId)
fun updateLessonRx(lessonEntity: LessonEntity) = lessonRepository.updateLessenDbRx(lessonEntity)
}
片段中获取列表的方法
private fun getListLessonDb(courseId: Int, context: Context) {
lessonViewModel.getListLessonFromDb(courseId).observe(viewLifecycleOwner, Observer {
setupRecyclerView(it, context)
})
}
更新行的方法
lessonViewModel.updateLessonRx(bookmarkLesson)
我应该怎么做,我应该修复哪个部分?
【问题讨论】:
标签: android mvvm android-room rx-java2