使用Rxjava更新和显示Room数据库中的数据



我使用MVVM架构模式用于房间数据库,当使用Livedata和更新行时,它会立即在recylerview中显示更改。

@Query("select * from lessons_table where course_id = :courseId")
fun getListLessonDb(courseId:Int):LiveData<List<LessonEntity>>

但我想在mvvm中使用Rxjava而不是livedata来显示数据和更改,但当更新数据行时,它不会立即在回收窗口中显示更改。这是我的代码:

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

LessonRepository

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



}

ViewModel

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)

我应该做什么?我应该修复哪个部分?

尝试在DAO 中将返回类型从Single<List<LessonEntity>>更改为Flowable<List<LessonEntity>>

相关内容

  • 没有找到相关文章

最新更新