我有ViewPager
有2个片段。当列表在一个片段上更新时,它应该反映另一个片段上的更改。
这是我的Dao
方法用于更新的方式
@Query("SELECT * FROM ${Constants.KAFANI_TABLE_NAME} WHERE isFavorite = 1")
fun getFavoriteKafani(): Single<MutableList<Kafana>>
@Query("UPDATE ${Constants.KAFANI_TABLE_NAME} SET isFavorite = :isFavorite WHERE id = :id")
fun setFavourite(id: Int, isFavorite: Int)
然后,我在repository
fun getFavoriteKafani(): Single<MutableList<Kafana>> {
return kafanaDao.getFavoriteKafani()
}
fun setKafanaFavorite(kafana: Kafana, isFavorite: Int): Completable = Completable.fromCallable {
kafanaDao.setFavourite(kafana.id, isFavorite)
}
我的ViewModel
fun setFavorite(kafana: Kafana, isFavorite: Int) {
compositeDisposable.addAll(kafanaRepository
.setKafanaFavorite(kafana, isFavorite)
.compose(scheduler.getSchedulersForCompletable())
.subscribeBy(
onComplete = {
sendFavoriteUpdate(1)
Timber.d("${Constants.KAFANA_APP_TAG} Added as favorite ${kafana.name}")
},
onError = {
Timber.d("${Constants.KAFANA_APP_TAG} setFavorite onError ${it.localizedMessage}")
}
))
}
fun loadFavoriteKafani() {
compositeDisposable.addAll(kafanaRepository
.getFavoriteKafani()
.compose(scheduler.getSchedulersForSingle())
.subscribeBy(
onSuccess = {
if (it.isEmpty()) {
isFavoriteEmpty.set(true)
Timber.d("${Constants.KAFANA_APP_TAG} loadFavoriteKafani listIsEmpty")
} else {
kafaniList.value = it
isFavoriteEmpty.set(false)
Timber.d("${Constants.KAFANA_APP_TAG} loadFavoriteKafani listNotEmpty")
}
},
onError = {
isFavoriteEmpty.set(true)
Timber.d("${Constants.KAFANA_APP_TAG} loadFavoriteKafani OnError: $it.localizedMessage")
}))
}
最后在我的fragment
private fun getFavoriteKafani() {
viewModel.loadFavoriteKafani()
viewModel.kafaniList.observe(this, Observer<MutableList<Kafana>> {
it?.let {
sorted = it.sortedWith(compareBy({ !it.isSponsored }, { it.name })).toMutableList()
kafanaAdapter = KafanaAdapter(sorted, this, 2)
binder.rvKafani.adapter = kafanaAdapter
}
})
}
但每当我在一个片段中将kafana设置为收藏时,该列表就不会在另一个片段中触发。