I'm working on an Android App. I have a list of photos loaded in memory. I want to make use of Reactive library, so I declare a memory-base datasource where I save the list:
@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
}
}
Then, I have a ViewModel where I call these methods:
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
}
}
Finally, I subscribe in my application:
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()
Listing and adding images work nicely. However, when I press the delete button, which publish in the onDelete subject, the snackbar is shown, but no change is performed to the RecyclerView adapter. Debugging, I noticed that the removePhoto
function is being called in MemoryPhotosSource
class, and the list is being successfuly modified. However, it does not emit the changes, that's why the RecyclerView is not updated. I confirmed this behavior by leaving the application and entering again, which forced the repainting of the Recycler, and then, the removed element didn't show up, as it should be. So, I think the problem is the list doesn't emit the changes when an item is removed.
Does anybody know a way to solve this? Any help would be much appreciated.
Thanks!