【发布时间】:2018-06-20 13:53:49
【问题描述】:
我正在开发一个 Android 应用程序。我在内存中加载了一张照片列表。我想使用 Reactive 库,所以我声明了一个基于内存的数据源来保存列表:
@Singleton
class MemoryPhotosSource @Inject constructor() {
var photos: MutableList<Image> = mutableListOf()
...
// Here is my function to add items to list.
fun addPhoto(image: Image) {
photos.add(image)
}
// Here is my function to list the items.
fun listPhotos(): List<Image> = photos
// Here is my function to remove items from list.
fun removePhoto(image: Image): Image {
photos.remove(image)
return image
}
}
然后,我有一个 ViewModel,我在其中调用这些方法:
class CreateDocumentFromPhotosViewModel @Inject constructor(): ViewModel() {
@Inject
lateinit var source: MemoryPhotosSource
fun listImages(): Observable<List<Image>> = Observable.fromCallable {
source.listPhotos()
}.applySchedulers()
fun addImage(image: Image) {
source.addPhoto(image)
}
fun removeImage(image: Image): Image {
source.removePhoto(image)
return image
}
}
最后,我在我的应用程序中订阅:
dis add viewModel.listImages()
.subscribe {
adapter.data = it
}
dis add onDelete
.map { viewModel.removeImage(it) }
.map { showSnackbar(parentView, resources.getString(R.string.document_removed), resources.getString(R.string.undo), it)}
.map { it.subscribe { viewModel.addImage(it) } }
.subscribe()
列出和添加图像效果很好。但是,当我按下在 onDelete 主题中发布的删除按钮时,会显示小吃栏,但不会对 RecyclerView 适配器进行任何更改。调试,我注意到removePhoto 函数在MemoryPhotosSource 类中被调用,并且列表正在被成功修改。但是,它不会发出更改,这就是 RecyclerView 没有更新的原因。我通过离开应用程序并再次进入来确认此行为,这会强制重新绘制 Recycler,然后,删除的元素没有出现,因为它应该是。所以,我认为问题是列表在删除项目时不会发出更改。
有人知道解决这个问题的方法吗?任何帮助将不胜感激。
谢谢!
【问题讨论】:
标签: android kotlin reactive-programming rx-kotlin